React Best Practices

Chapter 3 · Practice 4 of 4

Fetch data through your framework, or guard effect fetches against races

From Effects, and when you do not need one

Why it matters

Fetching in an effect has well known problems: waterfalls, no caching, no server rendering, and race conditions where an older response arrives last and overwrites newer results.

Pick the right tool for your setup:

  • Framework such as Next.js: fetch on the server in Server Components.
  • Client-only app: use a data library such as TanStack Query or SWR.
  • Effect fetch as a last resort: ignore stale responses with a flag or an AbortController in the cleanup.

If you do fetch in an effect, move the logic into a custom hook so every component does not repeat it.

Example

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