Chapter 3 · Practice 4 of 4
Fetch data through your framework, or guard effect fetches against races
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
AbortControllerin the cleanup.
If you do fetch in an effect, move the logic into a custom hook so every component does not repeat it.
Example
useEffect(() => {
let ignore = false;
fetchResults(query).then((json) => {
if (!ignore) setResults(json);
});
return () => {
ignore = true;
};
}, [query]);