React › Effects & Lifecycle
How would you fetch data safely inside useEffect while avoiding a common bug called a race condition?
AdvancedAnswer
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.