Skip to main content

Lesson 2 of 8

Async Patterns in React

Async state management in React has consistent pitfalls: race conditions when dependencies change rapidly, state updates after unmount, and missing loading/error branches. A standardized useAsync hook encapsulates all these concerns in one place.

25 minBy Priygop Editorial TeamUpdated 2026Peer Reviewed & Verified

The useAsync Hook - Production Pattern

The useAsync Hook - Production Pattern
import { useState, useCallback } from 'react';

// Standardized async state shape used consistently across the app
type AsyncStatus = 'idle' | 'loading' | 'success' | 'error';

interface AsyncState<T> {
  status: AsyncStatus;
  data: T | null;
  error: Error | null;
}

interface UseAsyncReturn<T, Args extends unknown[]> {
  status: AsyncStatus;
  data: T | null;
  error: Error | null;
  isIdle: boolean;
  isLoading: boolean;
  isSuccess: boolean;
  isError: boolean;
  execute: (...args: Args) => Promise<T | undefined>;
  reset: () => void;
}

function useAsync<T, Args extends unknown[] = []>(
  asyncFunction: (...args: Args) => Promise<T>
): UseAsyncReturn<T, Args> {
  const [state, setState] = useState<AsyncState<T>>({
    status: 'idle',
    data: null,
    error: null,
  });

  const execute = useCallback(async (...args: Args): Promise<T | undefined> => {
    setState({ status: 'loading', data: null, error: null });
    try {
      const data = await asyncFunction(...args);
      setState({ status: 'success', data, error: null });
      return data;
    } catch (err) {
      setState({ status: 'error', data: null, error: err instanceof Error ? err : new Error(String(err)) });
      return undefined;
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []); // asyncFunction assumed stable; pass it via useCallback if needed

  const reset = useCallback(() => {
    setState({ status: 'idle', data: null, error: null });
  }, []);

  return {
    ...state,
    isIdle: state.status === 'idle',
    isLoading: state.status === 'loading',
    isSuccess: state.status === 'success',
    isError: state.status === 'error',
    execute,
    reset,
  };
}

// Usage - clean component with no async boilerplate
function DeleteButton({ userId, onDeleted }: { userId: string; onDeleted: () => void }) {
  const { isLoading, isError, error, execute } = useAsync(deleteUser);

  async function handleDelete() {
    if (!confirm('Are you sure?')) return;
    const result = await execute(userId);
    if (result !== undefined) onDeleted();
  }

  return (
    <>
      <button onClick={handleDelete} disabled={isLoading}>
        {isLoading ? 'Deleting...' : 'Delete User'}
      </button>
      {isError && <p style={{ color: 'red' }}>{error?.message}</p>}
    </>
  );
}

Tip

Tip

Practice Async Patterns in React in small, isolated examples before integrating into larger projects. Breaking concepts into small experiments builds genuine understanding faster than reading alone.

Diagram
Loading diagramโ€ฆ

Visual architecture and flow for Async Patterns in React

Practice Task

Note

Practice Task - (1) Write a working example of Async Patterns in React from scratch without looking at notes. (2) Modify it to handle an edge case (empty input, null value, or error state). (3) Share your solution in the Priygop community for feedback.

Quick Quiz

Common Mistake

Warning

A common mistake with Async Patterns in React is skipping edge case testing - empty inputs, null values, and unexpected data types. Always validate boundary conditions to write robust, production-ready react code.

Hands-on Practice Tools for this Course

Test what you learn using these free in-browser developer utilities (no signup required).

All 40+ Tools

Topics in This Module

0/8 done