Async & APIIntermediateSSR-safehooks/async/useAsync.ts

useAsync

Auto-run async function with status.

Import

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

API

Signature

useAsync(fn, deps?, options?) → AsyncState & { execute, refetch }

When to use

Use useAsync 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 · useAsync
Editor
async function loadUser() {
  const res = await fetch('/api/users');
  return res.json();
}

function User() {
  const { data, loading, error, refetch } = useAsync(loadUser, []);
  if (loading) return <p>Loading…</p>;
  if (error) return <p>{String(error)}</p>;
  return <button onClick={() => void refetch()}>{JSON.stringify(data)}</button>;
}
Preview

Implementation source

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

hooks/async/useAsync.ts
import { useEffect } from 'react';
import { useAsyncFn } from './useAsyncFn';

export interface UseAsyncOptions {
  /** @default true */
  immediate?: boolean;
}

/**
 * Auto-running async effect with loading/error/data state.
 */
export function useAsync<TData, E = Error>(
  fn: () => Promise<TData>,
  deps: unknown[] = [],
  options: UseAsyncOptions = {},
) {
  const { immediate = true } = options;
  const [state, execute] = useAsyncFn<[], TData, E>(fn, deps);

  useEffect(() => {
    if (immediate) {
      void execute();
    }

  }, deps);

  return { ...state, execute, refetch: execute };
}

Copy-paste example

useAsync.example.tsx
'use client';

import { useAsync } from '@/hooks';

async function loadUser() {
  const res = await fetch('/api/users');
  return res.json();
}

export function User() {
  const { data, loading, error, refetch } = useAsync(loadUser, []);
  if (loading) return <p>Loading…</p>;
  if (error) return <p>{String(error)}</p>;
  return <button onClick={() => void refetch()}>{JSON.stringify(data)}</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/useAsync.ts for implementation details