Important: This documentation covers Yarn 1 (Classic).
For Yarn 2+ docs and migration guide, see yarnpkg.com.

Package detail

@chengsokdara/react-hooks-async

github:chengsokdara11.5kMIT0.0.2TypeScript support: included

Asynchronous React Hooks

react, hook, hooks, async, promise, await, asynchronous, use, useEffect, useCallback

readme

Asynchronous React Hooks

Write React hooks in asynchronous way


Try out useWhisper a React hook for OpenAI Whisper API

https://github.com/chengsokdara/use-whisper

  • Install

npm i @chengsokdara/react-hooks-async

yarn add @chengsokdara/react-hooks-async

  • Usage

  • useCallbackAsync
import { useCallbackAsync } from '@chengsokdara/react-hooks-async'

const App = () => {
  const sampleCallback = useCallbackAsync(
    // will be wrapped in try catch
    async () => {
      await promiseFunction()
    },
    // Optional: catch error
    (err) => {
      console.error(err)
    },
    // dependency list
    []
  )

  return (
    <div>
      <button onClick={() => sampleCallback()}>Fire</button>
    </div>
  )
}
  • useEffectAsync
import { useEffectAsync } from '@chengsokdara/react-hooks-async'
import { useState } from 'react'

const App = () => {
  const [state, setState] = useState<boolean>(false)

  useEffectAsync(
    // will be wrapped in try catch
    async () => {
      const response = await callBackend()
      setState(result.data)
    },
    // Optional: cleanup function when component unmounted
    () => {
      setState(undefined)
    },
    // Optional: catch error
    (err) => {
      console.error(err)
    },
    // dependency list
    []
  )

  return (
    <div>
      <p>
        <b>State:</b> {state}
      </p>
    </div>
  )
}
  • useMemoAsync
import { useMemoAsync } from '@chengsokdara/react-hooks-async'

const App = () => {
  const memoizedValue = useMemoAsync(
    // will be wrapped in try catch
    async () => {
      const response = await promiseFunction()
      return response + 1
    },
    // Optional: catch error
    (err) => {
      console.error(err)
    },
    // dependency list
    []
  )

  return (
    <div>
      <p>
        <b>Value:</b> {memoizedValue}
      </p>
    </div>
  )
}
  • Roadmap

    • add useTransition
    • add useLayoutEffect
    • add useImperativeHandle

Contact me for web or mobile app development using React or React Native
https://chengsokdara.github.io

changelog

Changelog

All notable changes to this project will be documented in this file.

The format is based on Keep a Changelog, and this project adheres to Semantic Versioning.

[Unreleased]

[0.0.3] - 2023-04-01

Added

  • add useTransition
  • add useLayoutEffect
  • add useImperativeHandle

[0.0.2] - 2023-03-09

Added

  • useMemoAsync
  • this changelog

Changed

  • useEffect depsOrDest is not optional, pass undefined or null to skip

[0.0.1] - 2023-03-08

Added

  • useCallbackAsync
  • useEffectAsync