Skip to content

useAsync

Saurav-TB-Pandey edited this page Aug 8, 2026 · 2 revisions

useAsync

Manage complex asynchronous data fetching with a clean state object. This hook handles loading states, error catching, data storage, and prevents stale responses automatically.

Usage Examples

Basic (Minimum Parameters)

The simplest possible implementation, executing immediately.

import { useAsync } from 'react-hook-lab';

function BasicUser() {
  const { data, loading, error } = useAsync(() => fetch('/api/user').then(res => res.json()));

  if (loading) return <div>Loading...</div>;
  if (error) return <div>Error!</div>;
  return <div>{data?.name}</div>;
}

Common (Standard Usage)

The most frequent real-world implementation, using dependencies to refetch when an ID changes.

import { useAsync } from 'react-hook-lab';

function UserProfile({ userId }) {
  const { data, loading, error, retry } = useAsync(
    () => fetch(`/api/users/${userId}`).then(res => res.json()),
    [userId]
  );

  if (loading) return <div>Loading spinner...</div>;
  if (error) return <div>Error: {error.message} <button onClick={retry}>Retry</button></div>;
  return <div>Welcome, {data?.name}</div>;
}

Advanced (All Parameters)

An exhaustive example utilizing every possible configuration option, including deferred execution and initial data.

import { useAsync } from 'react-hook-lab';

function AdvancedDashboard({ query }) {
  const { data, loading, error, execute, reset } = useAsync(
    async () => {
      const response = await fetch(`/api/search?q=${query}`);
      if (!response.ok) throw new Error('Search failed');
      return response.json();
    },
    [query],
    {
      immediate: false, // Wait for manual execution
      initialData: { results: [] } // Provide initial fallback data
    }
  );

  return (
    <div>
      <button onClick={execute} disabled={loading}>Run Search</button>
      <button onClick={reset}>Reset</button>
      {loading && <p>Searching...</p>}
      {error && <p>Error: {error.message}</p>}
      <ul>
        {data.results.map(item => <li key={item.id}>{item.name}</li>)}
      </ul>
    </div>
  );
}

API Reference

Parameters

  • asyncFunction (Required)
    • Type: () => Promise<T>
    • Description: The asynchronous function to execute. It must return a Promise.
  • dependencies
    • Type: any[]
    • Default: []
    • Description: Standard React dependency array. When these values change, the asyncFunction is re-evaluated and automatically executed (unless immediate: false).
  • options
    • Type: UseAsyncOptions<T>
    • Default: {}
    • Description: Configuration object.
      • immediate: (boolean, default: true) If true, the asyncFunction executes immediately on mount and when dependencies change. If false, it waits for execute() to be called.
      • initialData: (T, default: undefined) The initial value of data before the first execution completes.

Return Object

Returns UseAsyncReturn<T>:

  • data (T | undefined): The resolved data from the promise, or initialData.
  • error (Error | null): The caught error if the promise rejects.
  • loading (boolean): True while the promise is in-flight.
  • execute (() => Promise<T | undefined>): Function to manually trigger the async operation.
  • retry (() => Promise<T | undefined>): Function to re-execute the async operation (identical to execute).
  • reset (() => void): Function to clear errors, stop loading, and revert data back to initialData.

Clone this wiki locally