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

Implementing the Ignore Flag Pattern

Writing the complete pattern with let ignore = false in the effect and ignore = true in cleanup.

Implementing the Ignore Flag Pattern

What you'll learn: How to write the complete ignore flag pattern in useEffect to prevent race condition bugs when fetching data.

The Complete Pattern

Now that you understand why the ignore flag works, let's write the exact code pattern you'll use repeatedly.

The pattern has two parts:

  1. Inside the effect: Declare let ignore = false at the very top, then check if (!ignore) before setting state with your fetched data
  2. In the cleanup function: Return a function that sets ignore = true

Here's the complete implementation:

useEffect(() => {
  let ignore = false;

  async function fetchData() {
    const response = await fetch(`/api/users/${userId}`);
    const data = await response.json();
    
    if (!ignore) {
      setUser(data);
    }
  }

  fetchData();

  return () => {
    ignore = true;
  };
}, [userId]);

How It Works Step-by-Step

  1. Effect runs, creating a fresh ignore variable set to false
  2. Async fetch begins
  3. If the effect runs again (new userId), cleanup runs first, flipping the previous ignore to true
  4. A new effect starts with a new ignore = false
  5. When old fetch completes, its if (!ignore) check fails—it sees ignore = true from cleanup
  6. When new fetch completes, its ignore is still false, so state updates happen

The Closure Magic

Each effect execution creates its own closure with its own ignore variable. The cleanup function "remembers" which specific ignore to flip.

Key Takeaway: The ignore flag pattern always follows this structure: declare let ignore = false at the top of your effect, guard state updates with if (!ignore), and return a cleanup function that sets ignore = true.