Async & APIIntermediateSSR-safehooks/async/useRetry.ts

useRetry

Retry with exponential backoff.

Import

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

API

Signature

useRetry(fn, options?) → { run, cancel, attempt, error, loading }

When to use

Use useRetry 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 · useRetry
Editor
function FragileCall() {
  const { run, loading, attempt, error } = useRetry(
    async () => {
      const res = await fetch('/api/users');
      if (!res.ok) throw new Error('fail');
      return res.json();
    },
    { retries: 3, delayMs: 400, backoff: true },
  );

  return (
    <button onClick={() => void run()} disabled={loading}>
      Try (attempt {attempt}) {error?.message}
    </button>
  );
}
Preview

Implementation source

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

hooks/async/useRetry.ts
import { useCallback, useRef, useState } from 'react';
import { useIsMounted } from '../utility/useIsMounted';

export interface UseRetryOptions {
  retries?: number;
  delayMs?: number;
  backoff?: boolean;
  onRetry?: (attempt: number, error: Error) => void;
}

/**
 * Wraps an async function with retry + exponential backoff.
 */
export function useRetry<TArgs extends unknown[], TData>(
  fn: (...args: TArgs) => Promise<TData>,
  options: UseRetryOptions = {},
) {
  const { retries = 3, delayMs = 500, backoff = true, onRetry } = options;
  const isMounted = useIsMounted();
  const [attempt, setAttempt] = useState(0);
  const [error, setError] = useState<Error | null>(null);
  const [loading, setLoading] = useState(false);
  const abortRef = useRef(false);

  const run = useCallback(
    async (...args: TArgs): Promise<TData | undefined> => {
      abortRef.current = false;
      setLoading(true);
      setError(null);
      let lastError: Error | null = null;

      for (let i = 0; i <= retries; i += 1) {
        if (abortRef.current) break;
        if (isMounted()) setAttempt(i);
        try {
          const result = await fn(...args);
          if (isMounted()) {
            setLoading(false);
            setError(null);
          }
          return result;
        } catch (e) {
          lastError = e instanceof Error ? e : new Error(String(e));
          if (i < retries) {
            onRetry?.(i + 1, lastError);
            const wait = backoff ? delayMs * 2 ** i : delayMs;
            await new Promise((r) => setTimeout(r, wait));
          }
        }
      }

      if (isMounted()) {
        setError(lastError);
        setLoading(false);
      }
      return undefined;
    },
    [fn, retries, delayMs, backoff, onRetry, isMounted],
  );

  const cancel = useCallback(() => {
    abortRef.current = true;
    setLoading(false);
  }, []);

  return { run, cancel, attempt, error, loading };
}

Copy-paste example

useRetry.example.tsx
'use client';

import { useRetry } from '@/hooks';

export function FragileCall() {
  const { run, loading, attempt, error } = useRetry(
    async () => {
      const res = await fetch('/api/users');
      if (!res.ok) throw new Error('fail');
      return res.json();
    },
    { retries: 3, delayMs: 400, backoff: true },
  );

  return (
    <button onClick={() => void run()} disabled={loading}>
      Try (attempt {attempt}) {error?.message}
    </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/useRetry.ts for implementation details