Ignoring the Second Request's Result with a Flag
You'll learn how to use a simple boolean variable to discard outdated fetch responses when your effect has already moved on.
The Core Problem
In StrictMode (or any scenario where effects re-run), you might fire off a fetch, then immediately fire off another one. Both requests are now in-flight. Even if you can't cancel the first request, you can ignore its result when it comes back.
This is where a local flag variable inside your effect comes to the rescue.
The Pattern
useEffect(() => {
let ignore = false; // Flag starts as false
fetch('/api/data')
.then(res => res.json())
.then(data => {
if (!ignore) { // Only update state if flag is still false
setData(data);
}
});
return () => {
ignore = true; // Mark this effect's work as stale
};
}, []);
How It Works
When the cleanup function runs (before re-run or unmount), it flips ignore to true. Any pending .then() callbacks check that flag before updating state. If ignore is true, they silently do nothing.
This prevents the stale response from the first request from overwriting the fresh data from the second request.
Analogy
Imagine ordering food delivery, then immediately changing your order. The first driver still shows up, but you've left a note on your door: "Ignore this delivery—I reordered." The driver sees the note and leaves without you accepting the food.
Key Takeaway:
A boolean ignore flag lets your effect discard stale responses without actually canceling the network request—perfect for preventing race conditions when effects re-run.