0Pricing
Frontend Academy · Lesson

AbortController for Cleanup

Create an AbortController, pass its signal to fetch, and cancel in-flight requests in the cleanup function to prevent state updates on unmounted components.

Why Cancel Fetch Requests?

When a component unmounts or re-fetches, the previous request may still be in flight. If it resolves after the new request, stale data overwrites fresh data. AbortController cancels in-flight requests cleanly.

AbortController Basics

Create an AbortController, pass its signal to fetch, and call controller.abort() to cancel. Fetch throws an AbortError when aborted.

const controller = new AbortController();

try {
  const res = await fetch('/api/data', { signal: controller.signal });
  const data = await res.json();
  setData(data);
} catch (err) {
  if (err instanceof DOMException && err.name === 'AbortError') {
    console.log('Request was cancelled');
  } else {
    setError((err as Error).message);
  }
}

// To cancel:
controller.abort();

All lessons in this course

  1. useEffect Basics: Dependencies and Cleanup
  2. Fetching Data on Mount
  3. Handling Loading and Error States
  4. AbortController for Cleanup
← Back to Frontend Academy