Course contentsShow
← React
Lesson 589 of 2,39616. useEffect for Data FetchingFree lesson

The AbortController API Basics

Creating an AbortController, passing its signal to fetch, and calling abort() to cancel requests.

The AbortController API Basics

What you'll learn: How to use the browser's built-in AbortController to cancel fetch requests before they complete.

The Core Problem

When you start a fetch request in a useEffect, that request continues even if the component unmounts or the effect re-runs. You've seen how ignore flags help with race conditions, but they don't actually stop the network request—they just ignore the result. The browser keeps downloading data you'll never use.

What is AbortController?

AbortController is a browser API designed specifically to cancel ongoing operations like fetch requests. Think of it like a remote control for your network requests—you can press "stop" at any time.

The Three-Step Pattern

1. Create an AbortController:

const controller = new AbortController();

2. Pass its signal to fetch:

fetch('/api/data', { signal: controller.signal })

The signal property connects the controller to the fetch request. It's like giving fetch a listening device.

3. Call abort() to cancel:

controller.abort();

This immediately cancels the fetch. The promise will reject with an AbortError.

In useEffect

useEffect(() => {
  const controller = new AbortController();

  fetch('/api/data', { signal: controller.signal })
    .then(res => res.json())
    .then(data => setData(data))
    .catch(err => {
      if (err.name === 'AbortError') {
        console.log('Fetch cancelled');
      }
    });

  return () => controller.abort(); // Cleanup!
}, []);

When the effect cleans up (unmount or re-run), abort() fires and fetch stops immediately.

Key Takeaway: AbortController lets you truly cancel fetch requests by creating a controller, passing controller.signal to fetch, and calling controller.abort() in your cleanup function—actually stopping network activity instead of just ignoring results.