Skip to main content
Version: 0.2.0

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

PropertyTypeDefaultDescription
immediatebooleanfalseRun fn automatically on mount
onSuccess(data: T) => voidCalled when the promise resolves
onError(error: unknown) => voidCalled when the promise rejects

Return value

PropertyTypeDescription
status"idle" | "pending" | "fulfilled" | "rejected"Current lifecycle state
dataT | undefinedResolved value, or undefined
errorunknown | undefinedRejection reason, or undefined
loadingbooleantrue while status === "pending"
trigger(...args) => Promise<void>Manually fire the async function
reset() => voidReset state back to idle

Key behaviours

  • An AbortSignal is passed as the last argument to fn. Use it with fetch for 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...