Ignore Flags for Async Operations
What you'll learn: How to use boolean flags in effect cleanup to prevent outdated async results from updating state after a component unmounts or dependencies change.
The Race Condition Problem
When you make an async call (like fetching data) inside useEffect, the component might unmount or the effect might re-run before that async operation completes. If your code still tries to update state after that happens, you'll either get a warning about updating unmounted components or—worse—apply stale data to your current UI.
The Ignore Flag Pattern
The solution is a simple boolean flag that tells your async callback, "Hey, if you finish but this effect has already been cleaned up, ignore your results."
Here's the pattern:
useEffect(() => {
let ignore = false;
async function fetchData() {
const result = await fetch('/api/user');
const data = await result.json();
if (!ignore) {
setUser(data);
}
}
fetchData();
return () => {
ignore = true;
};
}, []);
How It Works
- Declare
ignoreasfalseat the start of the effect - Before updating state with async results, check
if (!ignore) - In the cleanup function, set
ignore = true
If the component unmounts or the effect re-runs, React calls cleanup first, flipping ignore to true. When your fetch completes, it checks the flag and skips the state update.
Think of it like leaving a note on your desk: "If I've left the room when you return, don't bother telling me the answer."
Key Takeaway: Use an ignore flag in effect cleanup to prevent async operations from updating state after the component has moved on, avoiding race conditions and memory leaks.