Async & APIIntermediateSSR-safehooks/async/useAbortController.ts

useAbortController

AbortController that aborts on unmount.

Import

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

API

Signature

useAbortController() → { signal, abort, reset, controller }

When to use

Use useAbortController 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 · useAbortController
Editor
function Cancellable() {
  const { signal, abort, reset } = useAbortController();

  async function load() {
    const controller = reset();
    await fetch('/api/users', { signal: controller.signal });
  }

  return (
    <>
      <button onClick={() => void load()}>Load</button>
      <button onClick={() => abort()}>Abort</button>
    </>
  );
}
Preview

Implementation source

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

hooks/async/useAbortController.ts
import { useCallback, useEffect, useRef } from 'react';

/**
 * Provides an AbortController that aborts on unmount and can be reset.
 */
export function useAbortController(): {
  controller: AbortController;
  signal: AbortSignal;
  abort: (reason?: unknown) => void;
  reset: () => AbortController;
} {
  const controllerRef = useRef(new AbortController());

  const abort = useCallback((reason?: unknown) => {
    controllerRef.current.abort(reason);
  }, []);

  const reset = useCallback(() => {
    controllerRef.current.abort();
    controllerRef.current = new AbortController();
    return controllerRef.current;
  }, []);

  useEffect(() => {
    return () => {
      controllerRef.current.abort();
    };
  }, []);

  return {
    get controller() {
      return controllerRef.current;
    },
    get signal() {
      return controllerRef.current.signal;
    },
    abort,
    reset,
  };
}

Copy-paste example

useAbortController.example.tsx
'use client';

import { useAbortController } from '@/hooks';

export function Cancellable() {
  const { signal, abort, reset } = useAbortController();

  async function load() {
    const controller = reset();
    await fetch('/api/users', { signal: controller.signal });
  }

  return (
    <>
      <button onClick={() => void load()}>Load</button>
      <button onClick={() => abort()}>Abort</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/useAbortController.ts for implementation details