useAsyncEffect

A React Hook similar to React.useEffect, but supports cancellable asynchronous functions.

Note

It should not return a cleanup function, as it is async and cannot synchronously return a cleanup function to be executed as expected.

If you need to clean up something, please use isCancelled() within UseAsyncEffectCallback to check the status of the Effect.

Scenes

  • Asynchronous Data Request Scenes: Implementing asynchronous data requests when the page loads or dependencies change
  • Status Update Monitoring Scenes: Executing asynchronous state synchronization updates after dependency state updates
  • Resource Cleanup and Cancellation Scenes: Implementing asynchronous operation cancellation and resource cleanup at the end of an Effect through isCancelled()
  • ...

Demo

Source

Try to click the button multiple times quickly.

Data:
none
Fetching:
false
Ignored count:
0

Usage

useAsyncEffect(async () => {}, [state]) useAsyncEffect(async (isCancelled) => { // do something async if(isCancelled()) return // do something when effect is not cancelled }, [state])

Source

Click links below to view source on GitHub.

API

useAsyncEffect(asyncCallback, deps)

AsyncCallback

An Effect callback that supports asynchronous functions, but does not support returning a cleanup function.

export type AsyncEffectCallback = (isCancelled: () => boolean) => void export type UseAsyncEffectCallback = AsyncEffectCallback

Deps

The same as React.useEffect.