CodePark/ questions / Effects
START PRACTICINGPRACTICE
Frontend question · React › Effects

What race condition can occur when fetching data in useEffect, and how do you prevent it?

useEffect(() => {
  let ignore = false;
  fetchResults(query).then(json => {
    if (!ignore) setResults(json);
  });
  return () => { ignore = true; };
}, [query]);

Responses can arrive out of order, so an old response can overwrite newer results. Prevent it with an effect cleanup that ignores or cancels the old request.

For example, the user types a, then ab. Now two requests are in flight. If the request for a is slower, its response lands last. It then overwrites the correct results for ab.

The fix is cleanup:

  • Keep an ignore flag in the effect, starting as false.
  • Set it to true in the cleanup.
  • Only call setState if it is still false.

When the dependency changes, React runs the old cleanup first. So stale responses are dropped. You can also pass an AbortController signal to fetch and call abort() in the cleanup. This cancels the request itself.

In practice, frameworks or libraries like TanStack Query handle caching, deduplication and races for you. So keep raw effect fetching simple.

  • Responses can arrive out of order and overwrite newer data.
  • Use an ignore flag that the cleanup function sets to true.
  • Or abort the request with AbortController in the cleanup.
  • Cleanup runs before the next effect, so stale results are thrown away.
  • Data libraries and frameworks handle caching and races for you.