Skip to content

Lesson 16 of 37Effects and beyond

Data Fetching

Load server data with loading, error, and success states, avoid race conditions, and know when to reach for a library.

19 min read0/6 questions

Almost every screen you build at work shows data from a server: a dashboard, a profile, search results. The fetch itself is one line. The hard part is everything around it: what the user sees while it loads, what happens when it fails, and what happens when two responses come back in the wrong order. Getting those right is what separates a demo from a product.

Three states, every time

A request is always in one of three states, and your UI needs a plan for each:

  • Loading: nothing to show yet. Show a spinner or a skeleton.
  • Error: the request failed. Say what happened and offer a retry.
  • Success: render the data (and handle the "empty list" case too).

A discriminated union (a type whose status field says which shape you have) makes impossible combinations, like "loading and also has an error", unrepresentable.

ReactLoadingStates.tsx
import { useEffect, useState } from "react"; type Post = { id: number; title: string }; // A fake API: 800 ms delay, fails if you ask it to.function fetchPosts(shouldFail: boolean): Promise<Post[]> { return new Promise((resolve, reject) => setTimeout(() => { if (shouldFail) reject(new Error("Server returned 500")); else resolve([ { id: 1, title: "Effects are for syncing" }, { id: 2, title: "Keys reset state" }, { id: 3, title: "Measure before you memo" }, ]); }, 800) );} type State = | { status: "loading" } | { status: "error"; message: string } | { status: "success"; posts: Post[] }; export default function App() { const [shouldFail, setShouldFail] = useState(false); const [state, setState] = useState<State>({ status: "loading" }); useEffect(() => { let ignore = false; fetchPosts(shouldFail) .then((posts) => { if (!ignore) setState({ status: "success", posts }); }) .catch((e: Error) => { if (!ignore) setState({ status: "error", message: e.message }); }); return () => { ignore = true; }; }, [shouldFail]); function toggleFailure() { setState({ status: "loading" }); setShouldFail(!shouldFail); } return ( <div> <button onClick={toggleFailure}>Reload with {shouldFail ? "success" : "a failure"}</button> {state.status === "loading" && <p>Loading posts...</p>} {state.status === "error" && <p style={{ color: "crimson" }}>Error: {state.message}</p>} {state.status === "success" && ( <ul>{state.posts.map((p) => <li key={p.id}>{p.title}</li>)}</ul> )} </div> );}

With the real browser API the shape is the same. One gotcha: fetch only rejects on network failure. A 404 or 500 still resolves, so check res.ok yourself:

const res = await fetch(`/api/posts?page=${page}`);
if (!res.ok) throw new Error(`Request failed: ${res.status}`);
const posts: Post[] = await res.json();
Quick check
The server answers a fetch call with HTTP 404. What happens to the promise?
Need a nudge? A hint rules out a wrong answer.

Search-as-you-type is where races bite. Type re, then rea: two requests go out. If the server answers re more slowly, its results land last and the list no longer matches the box. The ignore flag from the effects lesson fixes it, because React runs the previous effect's cleanup before starting the next one.

Toggle the checkbox off and type quickly to see the bug. The fake API is deliberately slower for short queries.

ReactRaceSearch.tsx
import { useEffect, useState } from "react"; const WORDS = ["react", "reach", "read", "ready", "reason", "redux", "reducer", "ref"]; function searchApi(q: string): Promise<string[]> { const delay = 1200 - q.length * 250; // short queries are slow return new Promise((resolve) => setTimeout(() => resolve(WORDS.filter((w) => w.startsWith(q))), Math.max(delay, 100)) );} export default function App() { const [query, setQuery] = useState(""); const [results, setResults] = useState<string[]>([]); const [useIgnore, setUseIgnore] = useState(true); useEffect(() => { if (!query) return; let ignore = false; searchApi(query).then((r) => { if (!useIgnore || !ignore) setResults(r); }); return () => { ignore = true; }; }, [query, useIgnore]); return ( <div> <label> <input type="checkbox" checked={useIgnore} onChange={(e) => setUseIgnore(e.target.checked)} /> Use ignore flag </label> <br /> <input type="text" value={query} onChange={(e) => setQuery(e.target.value)} placeholder="Type re, rea, read fast" /> <p>Showing results for the latest query: {results.join(", ") || "none"}</p> </div> );}

For real requests you can go one step further and cancel the network call with an AbortController:

useEffect(() => {
  const controller = new AbortController();
  fetch(`/api/search?q=${query}`, { signal: controller.signal })
    .then((res) => res.json())
    .then(setResults)
    .catch((e) => {
      if (e.name !== "AbortError") setError(e);
    });
  return () => controller.abort();
}, [query]);
Put it in order5 steps

With the ignore flag, the user types a then ab. Put the events in order.

  1. Tap the steps below in the right order.
Need a nudge? A hint shows where it starts.

Why data libraries exist

Hand-written effects work, but a real app repeats the same problems in every component: two components ask for the same user and send two requests; navigating back refetches data you had a second ago; a flaky request needs a retry; data goes stale and should refresh when the tab regains focus. Libraries like TanStack Query (formerly React Query) and SWR solve this once with a shared cache.

A query cache between components and the server
UserMenu: useQuery(['user', 7])UserMenuuseQuery(['user', 7])ProfilePage: useQuery(['user', 7])ProfilePageuseQuery(['user', 7])Query cache: key → data, status, ageQuery cachekey → data, status, ageAPI server: GET /users/7API serverGET /users/7subscribesubscribefetch once

Two components need user 7 at the same time. Both call useQuery with the same query key.

1/5
features/users/useUser.ts
import { useQuery } from "@tanstack/react-query";
 
export function useUser(id: number) {
  return useQuery({
    queryKey: ["user", id],
    queryFn: async () => {
      const res = await fetch(`/api/users/${id}`);
      if (!res.ok) throw new Error("Failed to load user");
      return res.json() as Promise<User>;
    },
    staleTime: 60_000, // treat data as fresh for a minute
  });
}
 
// In a component:
const { data, isPending, error } = useUser(7);

No effect, no ignore flag, no loading state by hand. Writes go through useMutation, and you tell the cache which keys to refetch afterwards.

Match the pairs0/5 matched

Match the TanStack Query feature to the problem it solves.

Choose an item, then its match on the other side.

React 19: use with Suspense

React 19 adds use(promise). A component calls it with a promise and React suspends that component until the promise settles. While it waits, the nearest <Suspense fallback={...}> shows its fallback. If the promise rejects, the nearest error boundary shows its error UI instead. Loading and error handling move out of the component and into the tree around it.

The promise must be created outside render, or cached, otherwise each render makes a new promise and React waits forever. Here a small cache does that job.

ReactUseSuspense.tsx
import { Component, Suspense, use, useState } from "react"; const cache = new Map<number, Promise<string>>();function fetchQuote(id: number): Promise<string> { if (!cache.has(id)) { cache.set(id, new Promise((resolve, reject) => setTimeout(() => (id === 3 ? reject(new Error("Quote 3 is missing")) : resolve(`Quote #${id}: ship small, ship often.`)), 700) )); } return cache.get(id)!;} function Quote({ id }: { id: number }) { const text = use(fetchQuote(id)); // suspends until resolved return <blockquote>{text}</blockquote>;} class ErrorBoundary extends Component<{ children: React.ReactNode }, { error: Error | null }> { state = { error: null as Error | null }; static getDerivedStateFromError(error: Error) { return { error }; } render() { if (this.state.error) return <p style={{ color: "crimson" }}>Could not load: {this.state.error.message}</p>; return this.props.children; }} export default function App() { const [id, setId] = useState(1); return ( <div> {[1, 2, 3].map((n) => <button key={n} onClick={() => setId(n)}>Quote {n}</button>)} <ErrorBoundary key={id}> <Suspense fallback={<p>Loading quote...</p>}> <Quote id={id} /> </Suspense> </ErrorBoundary> </div> );}

Error boundaries are still class components (or the small react-error-boundary package). The key={id} resets the boundary when you pick another quote.

Quick check
A component does const user = use(fetch('/api/me').then(r => r.json())) directly in its body. What goes wrong?
Need a nudge? A hint rules out a wrong answer.

Request waterfalls and how to start fetches early

The race-condition bug gives wrong data. The waterfall bug gives right data, slowly, and it is the most common reason a React screen feels sluggish in production.

A waterfall is a chain of requests where each one only starts after the previous one finished. In React it usually comes from the component tree itself. ProfilePage fetches the user in an effect and shows a spinner. Only when the user arrives does it render <Posts>, whose own effect then starts fetching posts. If <Posts> renders <Comments>, that is a third trip. Each request is fast on its own; together they stack.

One page, two loading strategies
  1. 0 ms

    Waterfall: user request starts

    ProfilePage mounts and its effect fetches the user. Posts are not rendered yet, so nobody has asked for them.

  2. 400 ms

    Waterfall: posts request starts

    The user arrives, Posts mounts, and only now does its effect start the posts request.

  3. 800 ms

    Waterfall: page complete

    Two round trips back to back. On a slow mobile network each one might be a second, not 400 ms.

  4. 0 ms

    Parallel: both requests start

    The page starts the user and posts requests at the same moment, because it knows it needs both.

  5. 400 ms

    Parallel: page complete

    Total time is the slowest request, not the sum of them.

Try both strategies. Each fake request takes 400 ms.

ReactWaterfall.tsx
import { useEffect, useState } from "react"; const wait = <T,>(ms: number, value: T) => new Promise<T>((r) => setTimeout(() => r(value), ms));const fetchUser = () => wait(400, { name: "Ada" });const fetchPosts = () => wait(400, ["Effects are for syncing", "Measure before you memo"]); function Posts({ start }: { start: number }) { const [posts, setPosts] = useState<string[] | null>(null); useEffect(() => { fetchPosts().then((p) => { setPosts(p); console.log(`waterfall finished after ${Math.round(performance.now() - start)} ms`); }); }, [start]); return posts ? <ul>{posts.map((p) => <li key={p}>{p}</li>)}</ul> : <p>Loading posts...</p>;} function WaterfallPage({ start }: { start: number }) { const [user, setUser] = useState<{ name: string } | null>(null); useEffect(() => { fetchUser().then(setUser); }, [start]); if (!user) return <p>Loading user...</p>; return <><h4>{user.name}</h4><Posts start={start} /></>; // Posts only mounts now} function ParallelPage({ start }: { start: number }) { const [data, setData] = useState<{ user: { name: string }; posts: string[] } | null>(null); useEffect(() => { Promise.all([fetchUser(), fetchPosts()]).then(([user, posts]) => { setData({ user, posts }); console.log(`parallel finished after ${Math.round(performance.now() - start)} ms`); }); }, [start]); if (!data) return <p>Loading...</p>; return <><h4>{data.user.name}</h4><ul>{data.posts.map((p) => <li key={p}>{p}</li>)}</ul></>;} export default function App() { const [mode, setMode] = useState<"waterfall" | "parallel" | null>(null); const [start, setStart] = useState(0); const run = (m: "waterfall" | "parallel") => { setStart(performance.now()); setMode(m); }; return ( <div> <button onClick={() => run("waterfall")}>Load as a waterfall</button> <button onClick={() => run("parallel")}>Load in parallel</button> {mode === "waterfall" && <WaterfallPage key={start} start={start} />} {mode === "parallel" && <ParallelPage key={start} start={start} />} </div> );}

The console shows roughly 800 ms for the waterfall and 400 ms in parallel. The fixes, in the order you should reach for them:

  • Start independent requests together. If a page needs A and B and neither depends on the other, start both at the top with Promise.all (or two useQuery calls in the same component, which run in parallel).
  • Hoist the request above the component that needs it. The route or page knows what the screen needs; leaf components do not. Start the fetch there and pass the data or the promise down.
  • Start in the event, not after the render. When a click will show a screen, start that screen's fetch in the click handler. By the time React has rendered the new screen, the request is already half done.
  • Accept the dependent ones. If posts genuinely need the user's id from the first response, the chain is real. Fix it on the server instead, with one endpoint that returns both, or with Server Components, where the round trips happen inside the data centre.

Suspense alone does not fix waterfalls. If each component creates its own promise when it first renders, nested boundaries still wait for each other. The fix is always who starts the request, and when.

Quick check
Each request takes 300 ms. Page fetches the user in an effect and shows a spinner. When the user arrives it renders <Posts> and <Sidebar> side by side, and each of those fetches its own data in an effect. Roughly how long until everything is on screen?
Need a nudge? A hint rules out a wrong answer.

use with a cached promise: render as you fetch

You saw in Transitions and Suspense that the promise given to use must be stable, and that someone has to own it. Here is the pattern that makes it fast as well as correct: a small cache that returns the same promise for the same key, and a preload function anyone can call early.

const cache = new Map<string, Promise<Product>>();
 
export function getProduct(id: string) {
  let promise = cache.get(id);
  if (!promise) {
    promise = fetchProduct(id);
    promise.catch(() => cache.delete(id)); // a failure should not be cached forever
    cache.set(id, promise);
  }
  return promise;
}
 
export const preloadProduct = (id: string) => void getProduct(id);

Because the same function serves both, a component can call use(getProduct(id)) during render and get the promise that a click handler, a hover, or a router started earlier. If it was started early enough, it has already resolved and the component renders immediately with no fallback at all. This is called render as you fetch: start the request, then render, instead of rendering and then fetching from an effect.

The cache needs the same care as any cache. Decide when an entry goes stale (a time-to-live, or clearing it after a mutation), evict rejected promises so a retry can succeed, and cap its size if keys are unbounded. Once you are writing all of that, you are rebuilding a data library, which is the signal to use one.

Prefetch on hover and intent

A user who moves the pointer onto a link is likely to click it within a few hundred milliseconds. That gap is enough to finish many requests. Prefetching on intent starts the request on onPointerEnter or onFocus (so keyboard users get it too), and the click finds the data already in the cache.

Hover over a product, wait a moment, then click it. Then try clicking a product you have not hovered over first, quickly.

ReactPrefetchOnHover.tsx
import { Suspense, use, useState, useTransition } from "react"; type Product = { id: string; name: string; price: string };const PRODUCTS = [ { id: "p1", name: "Desk lamp", price: "$39" }, { id: "p2", name: "Notebook", price: "$12" }, { id: "p3", name: "Headphones", price: "$89" },]; const cache = new Map<string, Promise<Product>>();function getProduct(id: string): Promise<Product> { if (!cache.has(id)) { console.log(`request started for ${id}`); cache.set(id, new Promise((r) => setTimeout(() => r(PRODUCTS.find((p) => p.id === id)!), 900))); } return cache.get(id)!;} function Details({ id }: { id: string }) { const product = use(getProduct(id)); return <p><strong>{product.name}</strong>: {product.price}</p>;} export default function App() { const [selected, setSelected] = useState<string | null>(null); const [isPending, startTransition] = useTransition(); return ( <div> {PRODUCTS.map((p) => ( <button key={p.id} onPointerEnter={() => getProduct(p.id)} onFocus={() => getProduct(p.id)} onClick={() => startTransition(() => setSelected(p.id))} > {p.name} </button> ))} <div style={{ opacity: isPending ? 0.5 : 1, minHeight: 40 }}> <Suspense fallback={<p>Loading details...</p>}> {selected ? <Details id={selected} /> : <p>Pick a product.</p>} </Suspense> </div> </div> );}

A hovered product opens instantly. An unhovered one keeps the old content dimmed for up to 900 ms, because the update is a transition and React waits rather than flashing the fallback.

With TanStack Query, the same idea is one call on the shared client:

const queryClient = useQueryClient();
 
<Link
  to={`/products/${id}`}
  onPointerEnter={() =>
    queryClient.prefetchQuery({
      queryKey: ["product", id],
      queryFn: () => fetchProduct(id),
      staleTime: 30_000, // without this, the page may refetch the data you just prefetched
    })
  }
/>

Frameworks do this for you at the route level. Next.js <Link> prefetches routes as they scroll into view in production; TanStack Router and React Router can preload a route's loader on hover or render. Know what your framework does before adding your own.

Prefetching has costs. It spends the user's data and your server's capacity on requests that may never be used, so do it for likely next steps, not every link on a page of hundreds. Never prefetch requests with side effects, and debounce hover prefetching on dense lists so sweeping the pointer across them does not fire twenty requests.

Fetching on the server (a preview)

Frameworks like Next.js let components run on the server. A Server Component can be async and simply await its data: no effect, no loading state in the browser, and secrets like database passwords never reach the client.

app/posts/page.tsx
export default async function PostsPage() {
  const res = await fetch("https://api.example.com/posts");
  const posts: Post[] = await res.json();
  return (
    <ul>
      {posts.map((p) => <li key={p.id}>{p.title}</li>)}
    </ul>
  );
}

You will build this properly in the Next.js course. For now, the rule of thumb: in a client-only React app, use a data library; in a framework, fetch on the server where you can.

Choosing: Server Components, TanStack Query, or a loader

In a real codebase the question is rarely "how do I fetch?" and usually "where should this fetch live?". There are three mature answers in 2026, and most large apps use more than one.

Server ComponentsTanStack QueryRoute loader
Where the fetch runsOn the server, during renderIn the browser, from a hookBefore the route renders (server or browser, depending on the router)
Typical stackNext.js App Router, other RSC frameworksAny React app: Vite SPA, React Native, alongside Next.jsReact Router (framework mode), TanStack Router, Remix-style apps
StrengthsNo client JavaScript for the fetch, direct database access, secrets stay on the server, no client waterfallA rich client cache: dedupe, retries, background refetch, optimistic updates, infinite scroll, pollingData starts loading at navigation time, so routes avoid waterfalls by design; pairs well with prefetch on intent
Weak spotsData that changes every few seconds while the page is open; highly interactive client stateNeeds care to avoid waterfalls; first load has to wait for JavaScript unless you prefetch on the serverData is tied to routes; a widget deep in the tree still needs another tool

A decision path that holds up in practice:

  1. Is the data needed for the first paint and the same for every visit of the page? Fetch it on the server (a Server Component or a loader), so the HTML arrives with it.
  2. Does the data keep changing while the user looks at it (a live dashboard, a chat, a list they edit), or does it need polling, infinite scroll, or optimistic updates? Use TanStack Query on the client. In Next.js you can do both: fetch on the server, then hand the data to TanStack Query as initial data and let the client keep it fresh.
  3. Is it a plain single-page app with a router? Use your router's loaders for route data, plus TanStack Query for the cache. TanStack Router and React Router both document this pairing.
  4. A small app or a one-off widget? An effect with an ignore flag is still a valid answer; just know what you are giving up.

Two details from TanStack Query v5 that often trip people reading older blog posts: cacheTime was renamed gcTime (how long unused data stays in memory), and the first-load flag is isPending (no data yet); isLoading now means "pending and currently fetching". staleTime (how long data counts as fresh) is a separate setting from gcTime, and setting it above zero is what stops a freshly mounted component from refetching immediately.

Whichever you choose, mutations need a plan for invalidation: after a write, which cached data is now wrong? With TanStack Query you call queryClient.invalidateQueries({ queryKey: ["todos"] }) in the mutation's onSuccess. With Server Components, a Server Action revalidates the affected path or cache tag. Actions and Optimistic UI covers the write side in depth.

Match the pairs0/5 matched

Match each screen to the data-fetching approach that fits best.

Choose an item, then its match on the other side.
ChallengeMedium

Loading, error, and retry

The fake API fetchTodos() takes 300 ms. The first call fails with Network down; later calls succeed.

Show all three states:

  • While loading: Loading...
  • On error: Error: Network down and a Try again button.
  • On success: a <ul> with one <li> per todo.

Try again shows Loading... again and refetches. Fetch in an effect and use an ignore flag in the cleanup so a stale response never sets state.

React
import { useEffect, useState } from "react"; let calls = 0;function fetchTodos(): Promise<string[]> { calls += 1; const attempt = calls; return new Promise((resolve, reject) => { setTimeout(() => { if (attempt === 1) reject(new Error("Network down")); else resolve(["Buy milk", "Walk the dog", "Ship the feature"]); }, 300); });} export default function App() { // Track the status (loading, error, success) and fetch in an effect. return <p>Loading...</p>;}
ChallengeMedium

Fix the race condition

This profile viewer has a bug. fetchUser answers at different speeds (user 1 takes 500 ms, user 2 takes 100 ms, user 3 takes 250 ms). Click User 3 and then quickly User 2: the screen ends on Priya even though User 2 (Sam) is selected, because the slower response arrives last and overwrites the faster one.

Fix it so the screen always shows the currently selected user:

  • Loading... while a request is in flight.
  • Name: <name> once the selected user's response arrives.

Keep fetchUser as it is. The fix belongs in the effect.

React
import { useEffect, useState } from "react"; const USERS: Record<number, { name: string; delay: number }> = { 1: { name: "Ada", delay: 500 }, 2: { name: "Sam", delay: 100 }, 3: { name: "Priya", delay: 250 },}; function fetchUser(id: number): Promise<string> { return new Promise((resolve) => setTimeout(() => resolve(USERS[id].name), USERS[id].delay), );} export default function App() { const [userId, setUserId] = useState(1); const [name, setName] = useState<string | null>(null); useEffect(() => { fetchUser(userId).then((result) => setName(result)); }, [userId]); function select(id: number) { setUserId(id); setName(null); } return ( <div> {[1, 2, 3].map((id) => ( <button key={id} onClick={() => select(id)}> User {id} </button> ))} <p>{name === null ? "Loading..." : "Name: " + name}</p> </div> );}
Key terms
loading / error / success
The three states every request passes through. Model them as one discriminated union so impossible combinations cannot happen.
AbortController
A browser API that cancels an in-flight fetch when you call abort(), usually from an effect's cleanup.
query key
The cache key in TanStack Query, such as ['user', 7]. Same key, same cached data; new key, new fetch.
stale-while-revalidate
Show cached data immediately, then refetch in the background and update if it changed.
Suspense
A boundary that shows a fallback while a child component is waiting, for example on use(promise) or a lazy component.
error boundary
A component that catches errors thrown while rendering its children and shows fallback UI.
request waterfall
Requests that run one after another because each starts only when an earlier one finished, often caused by fetching in nested effects.
render as you fetch
Starting a request before or while rendering (in a handler, loader, or preload) instead of after mount in an effect.
prefetch on intent
Starting a likely next request on hover or focus so the data is ready when the user clicks.
invalidation
Marking cached data as stale after a write so it is refetched, for example with invalidateQueries or revalidating a path.