useAsync
Manages the full lifecycle of an async function — idle, pending, fulfilled, and rejected — with built-in abort handling and optional auto-execution.
Signature
function useAsync<F extends (...args: any[]) => Promise<any>>(
fn: F,
options?: UseAsyncOptions<Awaited<ReturnType<F>>>
): UseAsyncReturn<F>
Options
| Property | Type | Default | Description |
|---|---|---|---|
immediate | boolean | false | Run fn automatically on mount |
onSuccess | (data: T) => void | — | Called when the promise resolves |
onError | (error: unknown) => void | — | Called when the promise rejects |
Return value
| Property | Type | Description |
|---|---|---|
status | "idle" | "pending" | "fulfilled" | "rejected" | Current lifecycle state |
data | T | undefined | Resolved value, or undefined |
error | unknown | undefined | Rejection reason, or undefined |
loading | boolean | true while status === "pending" |
trigger | (...args) => Promise<void> | Manually fire the async function |
reset | () => void | Reset state back to idle |
Key behaviours
- An
AbortSignalis passed as the last argument tofn. Use it withfetchfor automatic request cancellation. - Re-triggering while a request is in-flight cancels the previous request automatically.
- The abort controller is cleaned up on component unmount.
Live example
Loading playground...