Created
February 2, 2021 04:49
-
-
Save YajJackson/5993861e1202d36c9087c7c7e640f185 to your computer and use it in GitHub Desktop.
React hook for asynchronous state
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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