React Developer interview question · Most asked

What are the pitfalls of fetching data in `useEffect`, and how do you avoid race conditions?

Summary

Effects run after render (waterfalls), don't cache or dedupe, re-run in Strict Mode development, and can set state from stale responses when inputs change quickly (e.g., typing a search). Abort previous requests with AbortController or ignore outdated results with a cleanup flag.

Longer Answer

Prefer framework data loading (RSC, loaders) or TanStack Query/SWR, which handle caching, deduplication, retries and cancellation. If you must fetch in effects, always clean up.

Code Example

useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/search?q=${encodeURIComponent(query)}`, { signal: controller.signal })
    .then((r) => r.json())
    .then(setResults)
    .catch((err) => { if (err.name !== "AbortError") setError(err); });
  return () => controller.abort();
}, [query]);

Key Points

  • No caching/dedupe; render waterfalls
  • Race conditions with fast-changing inputs
  • Abort or ignore stale responses
  • Prefer query libraries or framework loaders

More most-asked React Developer questions

← All React Developer questions