Course contentsShow
← React
Lesson 401 of 2,39611. useState Patterns and PitfallsFree lesson

AbortController for Fetch Requests

Canceling in-flight requests with AbortController to prevent stale responses from updating state.

AbortController for Fetch Requests

What you'll learn: How to cancel in-flight fetch requests so stale responses don't overwrite your component's state.

The Problem with Long-Running Fetches

Imagine your user types in a search box. Your component fires off a fetch request for "apples". Before that response returns, they type again—now you fetch "oranges". If the "apples" response arrives after the "oranges" response (network timing is unpredictable), you'll display stale "apples" data even though the user searched for "oranges". This is the race condition from lesson 399, but now we have a better solution than ignore flags.

Enter AbortController

AbortController is a browser API that lets you cancel network requests mid-flight. You create a controller, pass its signal to fetch(), and call controller.abort() in your cleanup function:

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

  fetch(`/api/search?q=${query}`, { signal: controller.signal })
    .then(res => res.json())
    .then(data => setResults(data))
    .catch(err => {
      if (err.name === 'AbortError') {
        // Request was cancelled, ignore it
      } else {
        console.error(err);
      }
    });

  return () => controller.abort(); // Cancel on cleanup
}, [query]);

When query changes, React runs cleanup, which aborts the old request. The promise rejects with an AbortError, which you can safely ignore. The stale response never reaches your state setter.

Why This is Better Than Ignore Flags

With ignore flags (lesson 400), the response still arrives—you just discard it. With AbortController, you actively cancel the request, saving bandwidth and preventing unnecessary server processing.

Key Takeaway: Use AbortController in useEffect cleanup to cancel fetch requests when dependencies change or the component unmounts, preventing stale data from corrupting your state.