Part 11 / Topic 2 of 5
The race condition, reproduced for real
Fetching-in-an-effect has a race condition built in: nothing stops an earlier request from resolving after a later one, and whichever response arrives last simply overwrites results - correct or not. examples/02_race_condition_proven.jsx's RestaurantSearchRace has no protection against this at all:
// examples/02_race_condition_proven.jsx
export function RestaurantSearchRace({ query }) {
const [results, setResults] = useState([]);
useEffect(() => {
fetch(`/api/search?q=${query}`)
.then((res) => res.json())
.then((data) => setResults(data.results));
}, [query]);
return (
<ul aria-label="restaurant results">
{results.map((name) => <li key={name}>{name}</li>)}
</ul>
);
}
examples/02_race_condition_proven.test.jsx controls the race directly instead of hoping timing lines up: it renders with query="pizza", immediately rerenders with query="biryani", resolves "biryani"'s response first (the fast one, as a real second search normally would be), confirms the biryani results show up - and only then resolves "pizza"'s still-pending response. The screen really ends up showing the stale pizza results, overwriting the correct, newer biryani ones, exactly as a user watching their search box flicker back to an old answer would see. Nothing here depends on real timers or setTimeout; both requests are deferred promises this test resolves itself, in the order it chooses - the race is proven on purpose, not left to chance.
๐ Going deeper: an
ignoreflag set in the effect's cleanup function (checked before everysetState) is the minimal fix some codebases use - it stops the symptom (the stalesetStatecall) without stopping the request itself, which keeps running to completion anyway, wasting bandwidth and a server's time on an answer nobody will ever see. Section 3 reaches for the stronger fix instead.
Done here? The practice set for Part 11 โ including the solutions โ is on the part page.