Why Race Conditions Happen with Fetch in Effects
You'll learn why fetching data in effects naturally creates race conditions when requests resolve out of order.
The Core Problem
Race conditions occur in useEffect because async operations (like fetch) don't complete in the order they start. When a user triggers multiple fetches quickly—like typing in a search box—each keystroke fires a new effect. Even though the most recent search starts last, an earlier, slower request might finish after it, displaying stale results.
Think of it like ordering pizza from different restaurants. You order from Restaurant A at 2:00pm, then change your mind and order from Restaurant B at 2:05pm. Restaurant B delivers at 2:30pm (correct!), but then Restaurant A delivers at 2:45pm. If you accept the later delivery, you get the wrong pizza—one you didn't actually want.
Why Effects Don't Prevent This
When dependencies change and an effect re-runs, React doesn't automatically cancel the previous fetch. Both requests are "in flight" simultaneously. Whichever finishes last calls setState, regardless of which was most recent:
useEffect(() => {
fetch(`/api/search?q=${searchTerm}`)
.then(res => res.json())
.then(data => setResults(data)); // This runs whenever fetch completes!
}, [searchTerm]);
If searchTerm changes from "cat" → "dog" → "bird", you have three concurrent requests. If they resolve as bird → cat → dog, you'll display "dog" results when the user searched for "bird".
Why This is Inevitable
Network timing is unpredictable. Later requests don't automatically override earlier ones. Without explicit cancellation or tracking logic, your UI shows whichever response arrives last, not whichever is correct.
Key Takeaway: Race conditions happen because async operations resolve independently of when they started, and React effects don't automatically coordinate or cancel previous async work when dependencies change.