How would you fetch data safely inside useEffect while avoiding a common bug called a race condition?
Short answer
A race condition can happen when a component fetches data, the dependency changes again quickly, and an older, slower request finishes after a newer one, showing outdated results by mistake.
Advertisement
AModel answer
A race condition can happen when a component fetches data, the dependency changes again quickly, and an older, slower request finishes after a newer one, showing outdated results by mistake. You fix this by tracking whether the effect is still the current one, usually with a simple flag inside the cleanup function, and ignoring outdated results.
useEffect(() => {
let isCurrent = true;
fetchResults(query).then((data) => {
if (isCurrent) setResults(data);
});
return () => { isCurrent = false; };
}, [query]);Real-world example
A search box avoids showing outdated results when a user types quickly, by tracking whether each fetch request is still the most recent one before actually updating the results shown on screen.
Likely follow-ups
- How does this same problem get solved automatically by a library like React Query?
- What other approaches exist for canceling an outdated fetch request entirely?
Related topics