useAsyncEffect

useAsyncEffect is an custom hook for handling asynchronous side effects.

Import#

import { useAsyncEffect } from '@dwarvesf/react-hooks'

Usage#

Basic mount/unmount

useAsyncEffect(
async () => console.log('mount'),
() => console.log('unmount'),
[],
)

Omitting destroy

useAsyncEffect(async () => console.log('mount'), [])

Handle effect result in destroy

useAsyncEffect(
() => fetch('url'),
(result) => console.log(result),
)

Making sure it's still mounted before updating component state

useAsyncEffect(
async (isMounted) => {
const data = await fetch(`/users/${id}`).then((res) => res.json())
if (!isMounted()) return
setUser(data)
},
[id],
)

Parameters#

The API is the same as React's useEffect, except for some notable difference:

useAsyncEffect(callback, dependencies?)
useAsyncEffect(callback, onDestroy, dependencies?)
NameTypeDefaultDescription
callback(isMounted?:() => boolean) => Data \| Promise<Data>_The async callback that receieves a single function to check whether the component is still mounted.
onDestroy(result?: Data) => void_The callback is called when the component is unmounted.
dependenciesany[]_The dependencies array that will re-run the effect when the values within the array change.
Edit this page

Made with ❤️ by Dwarves Foundation