Async & APIIntermediateSSR-safehooks/async/useAsyncFn.ts

useAsyncFn

Manual async function with status.

Import

TypeScript
import { useAsyncFn } from '@/hooks';

API

Signature

useAsyncFn(fn, deps?) → [state, execute]

When to use

Use useAsyncFn instead of re-implementing the same pattern in multiple components.

SSR / Next.js

Client-side. Prefer RSC for first-paint server data.

Live playground

Edit the example and see it run against the real @/hooks package in this app.

Live playgroundEdit · run with real @/hooks · useAsyncFn
Editor
function SaveButton() {
  const [{ loading, error }, save] = useAsyncFn(async (payload: { name: string }) => {
    await fetch('/api/profile', { method: 'POST', body: JSON.stringify(payload) });
  });

  return (
    <button disabled={loading} onClick={() => void save({ name: 'Ada' })}>
      {loading ? 'Saving…' : 'Save'}
      {error ? String(error) : null}
    </button>
  );
}
Preview

Implementation source

Full library source for useAsyncFn — copy into your project when you are not installing a package yet.

hooks/async/useAsyncFn.ts
import { useCallback, useRef, useState } from 'react';
import type { AsyncState } from '../types';
import { useIsMounted } from '../utility/useIsMounted';

export type UseAsyncFnReturn<TArgs extends unknown[], TData, E = Error> = [
  AsyncState<TData, E> & { loading: boolean },
  (...args: TArgs) => Promise<TData | undefined>,
];

/**
 * Imperative async function wrapper (does not auto-run).
 * Guards against race conditions and unmounted updates.
 */
export function useAsyncFn<TArgs extends unknown[], TData, E = Error>(
  fn: (...args: TArgs) => Promise<TData>,
  deps: unknown[] = [],
): UseAsyncFnReturn<TArgs, TData, E> {
  const isMounted = useIsMounted();
  const callIdRef = useRef(0);
  const [state, setState] = useState<AsyncState<TData, E>>({
    status: 'idle',
    data: undefined,
    error: null,
    loading: false,
  });

  const execute = useCallback(async (...args: TArgs) => {
    const callId = ++callIdRef.current;
    setState((prev) => ({
      ...prev,
      status: 'loading',
      loading: true,
      error: null,
    }));

    try {
      const data = await fn(...args);
      if (!isMounted() || callId !== callIdRef.current) return undefined;
      setState({ status: 'success', data, error: null, loading: false });
      return data;
    } catch (error) {
      if (!isMounted() || callId !== callIdRef.current) return undefined;
      setState({
        status: 'error',
        data: undefined,
        error: error as E,
        loading: false,
      });
      return undefined;
    }

  }, deps);

  return [state, execute];
}

Copy-paste example

useAsyncFn.example.tsx
'use client';

import { useAsyncFn } from '@/hooks';

export function SaveButton() {
  const [{ loading, error }, save] = useAsyncFn(async (payload: { name: string }) => {
    await fetch('/api/profile', { method: 'POST', body: JSON.stringify(payload) });
  });

  return (
    <button disabled={loading} onClick={() => void save({ name: 'Ada' })}>
      {loading ? 'Saving…' : 'Save'}
      {error ? String(error) : null}
    </button>
  );
}

Production checklist

  • Called only from Client Components or other custom hooks
  • Type parameters filled in (e.g. useFetch<User[]>)
  • Tip: Abort in-flight work when the URL changes. Prefer null URL / enabled:false to skip.
  • Source of truth: open hooks/async/useAsyncFn.ts for implementation details