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:
- Inside the effect: Declare
let ignore = falseat the very top, then checkif (!ignore)before setting state with your fetched data - 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
- Effect runs, creating a fresh
ignorevariable set tofalse - Async fetch begins
- If the effect runs again (new
userId), cleanup runs first, flipping the previousignoretotrue - A new effect starts with a new
ignore = false - When old fetch completes, its
if (!ignore)check fails—it seesignore = truefrom cleanup - When new fetch completes, its
ignoreis stillfalse, 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.