Using a Boolean Flag in Effect Cleanup to Ignore Stale Responses
You'll learn how to use a simple boolean flag in your effect cleanup to prevent stale API responses from updating your component after it has moved on.
The Core Idea
When you make multiple asynchronous requests in quick succession (like typing in a search box), earlier requests might finish after later ones. Without protection, these out-of-order responses will incorrectly update your UI. The ignore flag pattern solves this by marking responses as "stale" when the effect re-runs or the component unmounts.
How It Works
You declare a boolean variable let ignore = false at the top of your effect. After your async operation completes, you check if (!ignore) before updating state. In the cleanup function, you set ignore = true. This tells any pending responses: "Don't update state—we've moved on."
useEffect(() => {
let ignore = false;
async function fetchData() {
const response = await fetch(`/api/search?q=${query}`);
const data = await response.json();
if (!ignore) {
setResults(data);
}
}
fetchData();
return () => {
ignore = true; // Mark this request as stale
};
}, [query]);
Why This Works
Each effect execution gets its own ignore variable. When query changes, the cleanup runs first, setting the old effect's ignore to true. The new effect starts with a fresh ignore = false. If the old fetch finishes late, it checks its own (now true) ignore flag and skips the state update.
Key Takeaway: The ignore flag pattern uses closure scope and cleanup functions to safely discard stale async results, preventing race conditions in data fetching effects.