useAsyncEffect
Runs asynchronous effect work with a current-generation guard and optional cleanup.
About
useAsyncEffect starts a promise-returning function after React commits an effect. The function receives shouldContinueEffect, which reports whether its component is still mounted and this invocation is still the newest one. Check it after each await before updating state.
The guard prevents stale work from committing results; it does not abort the underlying request or promise.
Examples
import { useState } from "react";
import { useAsyncEffect } from "rooks";
export default function AsyncGreeting() {
const [message, setMessage] = useState("Waiting…");
useAsyncEffect(async (shouldContinueEffect) => {
const value = await Promise.resolve("Hello from async work");
if (shouldContinueEffect()) setMessage(value);
}, []);
return <p role="status">{message}</p>;
}Parameters
| Argument | Type | Default | Meaning |
|---|---|---|---|
effect | (shouldContinueEffect: () => boolean) => Promise<T> | required | Starts the asynchronous work. |
deps | DependencyList | required | Uses React dependency comparison to start a new invocation. |
cleanup | (result: T | void) => void | undefined | Runs before the next invocation and on unmount. |
Return value
The hook returns void.
Behavior and lifecycle
Each new invocation receives a new call identifier. shouldContinueEffect() becomes false after a newer invocation starts or the component unmounts. Cleanup receives the resolved value only if the promise finished before cleanup; otherwise it receives undefined. The cleanup callback itself is kept fresh without restarting the effect.
The hook does not catch rejected promises. Catch expected failures inside effect to avoid an unhandled rejection. In development, React Strict Mode may replay effects, so async work must tolerate more than one start.
Compatibility and accessibility
The hook itself is server-safe because React effects do not run during server rendering. Browser APIs used inside effect, such as fetch or AbortController, still need their own support and cancellation strategy. Expose loading and error changes through an appropriate live region when users need feedback.