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

Using AbortController to Make Fetches StrictMode-Safe

Return a cleanup function that calls abort() to cancel the in-flight request when the component unmounts or re-runs.

Using AbortController to Make Fetches StrictMode-Safe

You'll learn how to return a cleanup function that cancels in-flight requests, preventing double-fetches in StrictMode and cleaning up properly when components unmount or re-run.

The Problem StrictMode Exposes

In development, StrictMode intentionally double-mounts components to help you find missing cleanup logic. When your useEffect fetches data without cleanup, React runs it twice—firing off two network requests. The first one becomes a "zombie fetch" that may still try to update state after the component has moved on.

The Solution: Cleanup with AbortController

When you create an AbortController inside your effect and pass its signal to fetch, you get a handle to cancel that specific request. The key is returning a cleanup function from your effect that calls controller.abort().

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.error(err);
      }
    });

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

Why This Works

When StrictMode (or a dependency change) causes your effect to re-run, React calls the cleanup function from the previous run first. That cleanup calls abort(), canceling the old request before the new one starts. On unmount, the same cleanup runs, preventing state updates on unmounted components.

Think of it like calling off a delivery truck that's already en route—you can't undo the request, but you can tell it "we don't need that anymore, stop trying to deliver."

Key Takeaway: Always return a cleanup function that calls controller.abort() when fetching in effects—it makes your component safe in StrictMode, prevents race conditions, and stops zombie requests from updating state after unmount.