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

The useEffect Cleanup Race Condition

How async operations in effects can set state after unmount and the cleanup function solution.

The useEffect Cleanup Race Condition

What you'll learn: Why async operations inside effects can cause errors after a component unmounts, and how cleanup functions prevent them.

The Problem

When you start an async operation (like fetch, setTimeout, or setInterval) inside a useEffect, that operation doesn't magically stop when your component unmounts. If the async work completes after the component is gone, trying to call setState will trigger a React warning about setting state on an unmounted component—or worse, cause unexpected bugs.

This is the cleanup race condition: your effect starts a race between the async operation finishing and the component unmounting. If unmount wins, but the async work tries to update state anyway, you have a problem.

useEffect(() => {
  fetch('/api/data')
    .then(res => res.json())
    .then(data => {
      setData(data); // ❌ Component might be unmounted!
    });
}, []);

The Cleanup Solution

Use a cleanup function to "cancel" or ignore the async work. A common pattern is a boolean flag that tracks whether the component is still mounted:

useEffect(() => {
  let isMounted = true;

  fetch('/api/data')
    .then(res => res.json())
    .then(data => {
      if (isMounted) {
        setData(data); // ✅ Only update if still mounted
      }
    });

  return () => {
    isMounted = false; // Cleanup: mark as unmounted
  };
}, []);

When the component unmounts, the cleanup function runs before the effect is destroyed, setting isMounted to false. If the fetch completes later, the condition prevents the setState call.

Key Takeaway: Async operations in effects can outlive the component—always use cleanup functions to prevent setting state after unmount and avoid race condition bugs.