useAsyncEffect()
useAsyncEffect(
effect,deps):void
Defined in: hooks/async/useAsyncEffect.ts:36
Run an async side effect with built-in cancellation on dependency change and unmount. The provided function receives an AbortSignal that can be used to cancel in-flight work (for example, fetch requests).
This is a small convenience wrapper on top of useEffect for "fire-and-forget" async work that should respond to dependency changes. The hook itself does not handle errors; you are expected to catch and handle them inside the provided effect callback.
On every run:
- A new
AbortControlleris created and itssignalis passed toeffect. - When dependencies change or the component unmounts, the previous controller is aborted, causing
signal.abortedto becometrue.
Parameters
effect
(signal) => void | Promise<void>
The async effect function. It receives an AbortSignal that can be passed to APIs which support cancellation (such as fetch).
deps
DependencyList
Dependency list, same semantics as useEffect.
Returns
void
Example
useAsyncEffect(async (signal) => {
const res = await fetch('/api/data', { signal });
if (!res.ok) {
throw new Error('Failed to fetch')
};
const json = await res.json();
// handle json...
}, [id]);