How do you fetch data in useEffect and avoid race conditions?
Quick answer
Use a cleanup flag or AbortController so a stale response from a previous dependency value is ignored.
In detail
When a dependency like a search query changes quickly, multiple requests are in flight and responses can arrive out of order, letting an old one overwrite the newest. Guard with an `active` flag set false in cleanup, or abort the previous request with AbortController. In real apps, a library like React Query/SWR handles this for you.
1useEffect(() => {
2 let active = true;
3 fetch(`/search?q=${q}`).then(r => r.json())
4 .then(d => { if (active) setResults(d); });
5 return () => { active = false; };
6}, [q]);Why interviewers ask this: A realistic senior-level scenario at product companies.
Common follow-up questions
- →Why prefer React Query over fetching in useEffect?
This is 1 of 118+ questions in the React Interview Kit
Get every question with detailed answers, follow-ups and real code — plus coding challenges and a last-minute revision sheet. One-time payment, instant access.
⚡ Get the React Interview Kit → ₹399