useAsyncState

A robust React hook for managing asynchronous operations and remote data fetching with integrated state tracking and retry logic.

Warning

Retries will not be triggered if a request is manually aborted or if the component unmounts during the process.

Important

When implementing optimistic updates via mutate, you must manually handle the state reversal inside a try/catch block within the execute call.

Tip

Use the params configuration to automatically serialize objects into URL query strings, avoiding manual string concatenation.

Installation

bash

Description

The useAsyncState hook provides a full-featured lifecycle management system for asynchronous requests. It eliminates the boilerplate of manually handling loading, error, and data states, while offering advanced features like automatic retries, request timeouts, URL parameter serialization, optimistic updates via mutate, and request cancellation via AbortController.

Parameters

NameTypeDescription
options.initialDataT | nullThe initial value for the data state. Default is null.
options.onSuccess(data: T) => voidGlobal callback triggered when any request initialed by this hook succeeds.
options.onError(error: Error) => voidGlobal callback triggered when a request fails after all retries are exhausted.

Return values

NameTypeDescription
dataT | nullThe current data returned by the last successful asynchronous operation.
errorError | nullThe error object if the last operation failed.
isLoadingbooleantrue if a request is currently in progress.
isErrorbooleantrue if the last operation resulted in an error.
isSuccessbooleantrue if the last operation completed successfully.
isIdlebooleantrue if no request has been initiated yet.
execute(url: string, config?: FetchConfig) => Promise<T | null>Function to trigger a new request with custom headers, params, and retry settings.
mutate(data: T) => voidDirectly updates the local data state (useful for optimist UI updates).
reset() => voidCancels pending requests and restores the state to its initial values.
retry() => Promise<T | null>Re-executes the last request using the exact same configuration and URL.

Demo

Async State

Click "Fetch Posts" to see results.

Source code

tsx