Skip to content

Instantly share code, notes, and snippets.

@YajJackson
Created February 2, 2021 04:49
Show Gist options
  • Save YajJackson/5993861e1202d36c9087c7c7e640f185 to your computer and use it in GitHub Desktop.
Save YajJackson/5993861e1202d36c9087c7c7e640f185 to your computer and use it in GitHub Desktop.
React hook for asynchronous state
import { useEffect, useState } from 'react'
import type { DependencyList } from 'react'
export const useAsyncMemo = <T>(
factory: () => Promise<T>,
deps: DependencyList,
initialState: T
) => {
const [state, setState] = useState<T>(initialState)
useEffect(() => {
let cancel = false
factory().then((value) => {
if (!cancel) setState(value)
})
return () => {
cancel = true
}
}, deps)
return state
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment