Skip to content

Instantly share code, notes, and snippets.

@mokadev90
Created January 29, 2024 14:16
Show Gist options
  • Select an option

  • Save mokadev90/d366551cb04f1e39dacc753f680db98e to your computer and use it in GitHub Desktop.

Select an option

Save mokadev90/d366551cb04f1e39dacc753f680db98e to your computer and use it in GitHub Desktop.
useAsync
import { useCallback, useEffect, useState } from "react"
export default function useAsync(callback, dependencies = []) {
const [loading, setLoading] = useState(true)
const [error, setError] = useState()
const [value, setValue] = useState()
const callbackMemoized = useCallback(() => {
setLoading(true)
setError(undefined)
setValue(undefined)
callback()
.then(setValue)
.catch(setError)
.finally(() => setLoading(false))
}, dependencies)
useEffect(() => {
callbackMemoized()
}, [callbackMemoized])
return { loading, error, value }
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment