The case for a data-fetching library

Intermediate · 11 min

Why hand-rolled useEffect fetching stops scaling — no caching, no dedup, no refetch-on-focus — and what a dedicated library buys you back.

Before thisData fetching in effectsCleanup and race conditions in effects

Theo - t3.gg · 11 min

The case for a data-fetching library

The player loads from youtube-nocookie.com when you press play. Nothing reaches YouTube before that.

Taught by Theo - t3.ggReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A hand-rolled fetch effect only knows about itself. Two components that both need the same user record will each fire their own request, because nothing shares state between them.
  • Caching, deduplication, refetch-on-window-focus, retry-on-failure, and race-condition safety are all separate problems that a raw useEffect fetch does not solve, and each one is real engineering work if you build it yourself.
  • Stale data is a silent failure. A component that fetched once on mount shows last week's price list forever unless someone remembers to refetch it, and nothing in the useEffect pattern reminds them.
  • A dedicated data-fetching library's job is to be the shared cache and the scheduler that every component's query reads from and writes to, instead of each component owning its own private fetch.
  • Rebuilding this yourself is possible, but it means maintaining a second, informal data layer parallel to your actual backend, and that maintenance cost compounds as the app grows.

The pattern that works, until it doesn’t

By now you’ve written the pattern many times: a useEffect that fires a fetch, a few pieces of useState for the data, loading, and error, and a cleanup flag so a slow response can’t overwrite a newer one.

function ProductPage({ id }) {
  const [product, setProduct] = useState(null);
  const [status, setStatus] = useState("idle");

  useEffect(() => {
    let cancelled = false;
    setStatus("loading");

    fetch(`/api/products/${id}`)
      .then((res) => res.json())
      .then((data) => {
        if (!cancelled) {
          setProduct(data);
          setStatus("success");
        }
      })
      .catch(() => {
        if (!cancelled) setStatus("error");
      });

    return () => {
      cancelled = true;
    };
  }, [id]);

  if (status === "loading") return <Spinner />;
  if (status === "error") return <ErrorMessage />;
  return <ProductCard product={product} />;
}

This is correct, in the narrow sense that it handles the race condition from the previous lesson. It also looks finished. It is not. The moment a second component on the same page needs that same product, the cracks show.

The problems that only appear at scale

Put a <ProductSummary id={id} /> in the header and a <ProductPage id={id} /> in the body, and you now have two independent useEffect fetches for the exact same resource. Neither knows the other exists. The network tab shows two requests; the server does twice the work; and if one response arrives a moment after the other, the two components can briefly render different prices for the same product.

That’s deduplication failing, and it’s the easy one to notice. The ones that bite later:

  • No cross-component cache. Navigate away from the product page and back, and the component fetches again from scratch — the data it already had is gone the instant it unmounts, because it only ever lived in that one component’s state.
  • No refetch on window focus. A user tabs away, someone restocks the product, they tab back — and the stale price sits there until they refresh the page, because nothing is watching for “the user just came back.”
  • No automatic retry. A flaky network blip fails the request once, and the component is stuck in its error state forever unless the user triggers a remount.
  • No shared loading/error state. Every component that fetches the same resource duplicates its own status state, and keeping them consistent with each other is now your job.

None of these are bugs in the code above — the code does exactly what it was written to do. They’re missing features, and every one of them is genuine engineering effort to build correctly. Cache invalidation, in particular, is notoriously easy to get subtly wrong.

What “a data-fetching library” actually means

The fix isn’t a bigger useEffect. It’s moving the fetch logic out of the component and into a shared layer that every component reads from and writes to — a client-side cache, keyed by what’s being fetched, that:

  • serves a cached value instantly if one exists, and refetches in the background to keep it fresh;
  • merges simultaneous requests for the same key into one network call;
  • knows how to invalidate or refetch a key when something relevant changes;
  • re-runs queries automatically on window focus or reconnect, because those are the moments data is most likely stale.

TanStack Query (formerly React Query) is the library this roadmap uses to teach these ideas, and it’s the dominant choice in the React ecosystem for exactly this reason: it turns “server data” from something every component manages for itself into something the whole app shares through one cache.

This lesson is deliberately about the problem, not the API. The next lesson introduces useQuery and shows the cache in action.

What the video covers

Theo’s video makes almost exactly this argument, crediting TkDodo’s well-known “Why You Want React Query” post as the source of the reasoning. He opens bluntly — don’t fetch in your useEffects — and walks through caching, deduplication, and refetch behavior as the concrete things you give up by not using a library, from lived experience rather than a side-by-side code demo. It’s a good gut-check on why this matters before you see the API. It assumes you’re already comfortable with React, and doesn’t write out a full hand-rolled useEffect example on screen the way the code above does, so use this lesson’s example to see the exact shape of the problem he’s describing.

Where this fits

The next lesson is TanStack Query fundamentals, where useQuery and query keys turn this argument into working code.

Check yourself

  1. 01Two sibling components both render the same product by id, each with its own useEffect fetch. What goes wrong, and why doesn't adding a loading spinner fix it?

    Both components fire independent network requests for the same data, so the server is hit twice and the two copies can briefly disagree if one request finishes before the other. A loading spinner only hides the symptom; it does not stop the duplicate request or give the two components a shared source of truth.

  2. 02What is request deduplication, and why can't a single useEffect block provide it across components?

    Deduplication means that when two callers ask for the same data at the same time, only one network request actually goes out and both callers receive its result. A useEffect block only has access to its own component's state, so it has no way to notice that another component just asked for the same thing.

  3. 03Why is 'stale data' a real bug and not just a minor inconvenience?

    A component that fetched once on mount keeps showing that snapshot indefinitely, even after the underlying data changes elsewhere, which means users can act on information that is already wrong. It is a correctness bug, because the UI claims to represent current state and does not.

  4. 04According to the lesson, what is the real alternative to writing more useEffect code to fix these problems?

    Reaching for a dedicated data-fetching library that owns a shared cache across the whole app, so caching, deduplication, refetching, and race-condition handling are solved once in the library rather than reimplemented in every component that needs data.

Go deeper

Notes

Private to you

Esc
↑↓ navigate↵ open? shortcuts

Keyboard shortcuts

Press Esc to close

Anywhere

⌘K
Search and commands
/
Search
?
This sheet
Esc
Close

Reading a lesson

J
Next lesson
K
Previous lesson
B
Bookmark