Skip to content

useAsync()

useAsync<T, Args, E>(asyncFunction, immediate?): UseAsyncResult<T, Args, E>

Defined in: hooks/async/useAsync.ts:75

A React hook to run an async function with managed loading, error, and result state. Useful for data fetching or any asynchronous work.

It also:

  • Ignores results from outdated calls when multiple requests are in flight.
  • Avoids updating state after the component has unmounted.

Type Parameters

T

T

The type of the resolved value.

Args

Args extends unknown[] = []

Tuple of argument types passed to the async function.

E

E = Error

The error type (defaults to Error).

Parameters

asyncFunction

(...args) => Promise<T>

The async function to execute.

immediate?

boolean = true

Whether to run once automatically on mount. Only use true when asyncFunction does not require arguments.

Returns

UseAsyncResult<T, Args, E>

An object with:

  • execute(...args): trigger the async function.
  • loading: whether the async operation is in progress.
  • error: the last error (if any).
  • result: the last successful result.

Example

tsx
import { useAsync } from '@zl-asica/react';

const fetchData = async () => {
  const response = await fetch('https://api.example.com/data');
  if (!response.ok) throw new Error('Failed to fetch data');
  return response.json();
};

const MyComponent = () => {
  const { execute, loading, error, result } = useAsync(fetchData, true);

  if (loading) return <p>Loading...</p>;
  if (error) return <p>Error: {error.message}</p>;

  return <div>Result: {JSON.stringify(result)}</div>;
};

Released under the MIT License.