Course contentsShow
← React
Lesson 557 of 2,39615. useEffect FundamentalsFree lesson

Cleanup for AbortController

Aborting in-flight fetch requests using AbortController.abort() in cleanup to handle race conditions and prevent stale updates.

Cleanup for AbortController

You'll learn how to cancel ongoing fetch requests when a component unmounts or when dependencies change, preventing race conditions and stale data bugs.

When you initiate a fetch request inside useEffect, the request continues even if your component unmounts or the effect re-runs with new data. This creates a race condition: an older request might finish after a newer one, causing stale data to overwrite fresh data. You might also try to update state in an unmounted component, triggering warnings.

The solution is AbortController. You create a controller, pass its signal to fetch, and call controller.abort() in your cleanup function. This cancels the in-flight request.

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

  fetch(`/api/user/${userId}`, { signal: controller.signal })
    .then(res => res.json())
    .then(data => setUser(data))
    .catch(err => {
      if (err.name === 'AbortError') {
        // Request was cancelled - this is expected, do nothing
      } else {
        console.error(err);
      }
    });

  return () => {
    controller.abort(); // Cancel request if userId changes or component unmounts
  };
}, [userId]);

When userId changes or the component unmounts, the cleanup function calls abort(). The fetch promise rejects with an AbortError, which you can safely ignore. This prevents the old request's response from updating your state.

Think of it like canceling a pizza delivery: if you change your mind and order from a different restaurant, you call the first restaurant to cancel so their delivery driver doesn't show up with the wrong order.

Key Takeaway: Always abort fetch requests in useEffect cleanup using AbortController.abort() to prevent race conditions and updates from stale requests.