Created
November 17, 2022 06:28
-
-
Save Phryxia/b03f8bc87998f4cc3c426efe3fba565f to your computer and use it in GitHub Desktop.
TypeScript implementation of useAsyncEffect hook for React
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 { DependencyList, EffectCallback, useEffect } from 'react' | |
| type Destructor = () => void | |
| type AsyncDestructor = () => Promise<void> | |
| type AsyncEffectCallback = () => Promise<void | Destructor | AsyncDestructor> | |
| export function useAsyncEffect(callback: EffectCallback | AsyncEffectCallback, deps?: DependencyList) { | |
| useEffect(() => { | |
| const mayPromise = callback() | |
| if (mayPromise instanceof Promise) { | |
| return () => void mayPromise.then(cleanup => cleanup?.()) | |
| } | |
| return mayPromise | |
| }, deps) | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Fetching asynchronous API inside of normal
useEffectusually really sucks. Still it's possible with vanilla React, but it's very verbose and reduces development experience.And even more, cleanup is more tricky when cleanup function depends on the return value of asynchonous things.
This custom hook wraps
useEffecteffectively. Also this hook is intended to replace normaluseEffectsince it works well with normal synchronous callback. Also asynchronous clean up is also available, though it should be carefully used.Note that these pre-defined types are based on React type declaration. The reason why I redeclared these is because some of them are not accessible from outside of the module.