@chengsokdara/react-hooks-async
TypeScript icon, indicating that this package has built-in type declarations

0.0.2 • Public • Published

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

Package Sidebar

Install

npm i @chengsokdara/react-hooks-async

Weekly Downloads

2,592

Version

0.0.2

License

MIT

Unpacked Size

10.4 kB

Total Files

27

Last publish

Collaborators

  • chengsokdara