Suspense for data fetching

Advanced · 20 min

How a <Suspense> boundary catches a component that is still waiting on data, shows a fallback, and lets useSuspenseQuery replace loading flags.

Before thisCaching, invalidation, and mutationsThe React Compiler and automatic memoization

tapaScript by Tapas Adhikary · 35 min · from 14:48

Suspense for data fetching

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

Taught by tapaScript by Tapas AdhikaryReport a problem with this video
Not started
Set this lesson's status

What you'll learn

  • A `<Suspense>` boundary wraps a subtree and shows its `fallback` prop whenever a descendant component is not yet ready to render.
  • A component becomes 'not ready' by suspending: it throws a promise instead of returning JSX, and React catches that throw at the nearest Suspense boundary above it.
  • You almost never throw a promise by hand. A Suspense-compatible data source does it for you — in practice today that means TanStack Query's `useSuspenseQuery` instead of `useQuery`.
  • `useSuspenseQuery` removes `isLoading` and `error` checks from the component body; the loading state is handled by the Suspense fallback, and the error state needs a separate error boundary.
  • One boundary can wrap several suspending components; React shows the fallback until every one of them is ready, then reveals the whole subtree at once.
  • Suspense for data fetching composes with caching: once TanStack Query has cached data for a key, mounting the same query again does not suspend, because the promise it would throw is already resolved.

The problem with loading flags

Every data-fetching pattern earlier in this roadmap follows the same shape: a component calls a hook, gets back { data, isLoading, error }, and the JSX branches on those three states by hand.

function ProductPage({ id }) {
  const { data, isLoading, error } = useQuery({
    queryKey: ["product", id],
    queryFn: () => fetchProduct(id),
  });

  if (isLoading) return <Spinner />;
  if (error) return <ErrorMessage error={error} />;
  return <ProductDetails product={data} />;
}

That works fine for one component. It gets awkward once a page has several independent data-fetching components nested inside each other: each one needs its own loading branch, and a page that fetches a product, its reviews, and its recommendations ends up with three separate spinners popping in at different times, in whatever order the network happens to resolve them.

Suspense moves the loading branch out of the component and up to a boundary that can cover many components at once.

Suspending: throwing a promise instead of rendering

A component “suspends” when, instead of returning JSX, it throws something that is not an error — a Promise. React treats a thrown promise as a signal: “I am not ready, try me again once this resolves.” It walks up the tree looking for the nearest <Suspense> ancestor, renders that boundary’s fallback in the meantime, and re-renders the suspended component once the promise settles.

import { Suspense } from "react";

function ProductPage({ id }) {
  return (
    <Suspense fallback={<Spinner />}>
      <ProductDetails id={id} />
    </Suspense>
  );
}

ProductDetails itself no longer branches on a loading state. If its data isn’t ready, it suspends, the Suspense boundary shows <Spinner />, and ProductDetails is simply not rendered at all until the data arrives — there is no “half-rendered with undefined data” state to guard against.

Nobody writes the throw by hand. It is the job of a data source built for this pattern, and for the last few years that data source, in practice, has been TanStack Query’s useSuspenseQuery.

useSuspenseQuery: the practical pairing

useSuspenseQuery has the same signature as useQuery, but a different contract: it never returns a loading or error state. If the data isn’t cached yet, it throws the in-flight promise so the surrounding Suspense boundary can catch it. If the fetch already succeeded (because TanStack Query cached it from an earlier mount, or another query shares the key), the hook returns immediately with data already populated — no suspension at all.

import { useSuspenseQuery } from "@tanstack/react-query";

function ProductDetails({ id }) {
  const { data: product } = useSuspenseQuery({
    queryKey: ["product", id],
    queryFn: () => fetchProduct(id),
  });

  // data is guaranteed to be present here — no isLoading check needed
  return <h1>{product.name}</h1>;
}

The component body gets simpler because an entire branch of possible states — “still loading” — has been deleted from it. That state still exists; it just lives in the Suspense boundary instead of in every component that fetches data.

This is also where the caching lesson earlier in this group pays off directly: useSuspenseQuery suspends only when there is no usable cached data for that query key. Navigate back to a product page you’ve already visited in this session, and the cached entry means the component resolves instantly with no fallback flash — the same cache that avoids a duplicate network request also avoids a duplicate loading spinner.

One boundary, many suspenders

A single Suspense boundary can wrap multiple components that each suspend independently.

<Suspense fallback={<PageSkeleton />}>
  <ProductDetails id={id} />
  <ProductReviews id={id} />
  <RecommendedProducts id={id} />
</Suspense>

React waits for all three to be ready before revealing any of them — the boundary either shows the fallback or shows the finished subtree, never a partial mix. If you want reviews and recommendations to appear independently once each is ready, you nest a separate Suspense boundary around each one instead of sharing a single outer boundary.

What the video covers

Tapas Adhikary’s video spends its first stretch walking through the fetch-on-render and fetch-then-render patterns that motivate Suspense, then at 14:48 introduces “A New Pattern: Data Fetching with React Suspense,” building a boundary and fallback around a component that suspends on data, before moving into error boundaries at 26:50. It is a genuinely hands-on build rather than a slide deck, which is worth watching for the shape of the code; it does not dwell on useSuspenseQuery specifically or on how caching changes repeat visits, which is why those two points get fuller treatment above.

Where this fits

Suspense gives you the fallback half of the story — what shows while data is pending. The other half is what shows when something goes wrong, which is the subject of the next lesson: error boundaries.

Check yourself

  1. 01What does a component actually do to tell React it is not ready to render yet?

    It throws a promise during render instead of returning JSX. React does not run special data-fetching logic itself; it only catches that thrown promise, shows the nearest Suspense boundary's fallback, and retries rendering the component once the promise resolves.

  2. 02Why do most React apps use `useSuspenseQuery` rather than throwing a promise manually?

    Writing a resource that caches and throws its own pending promise correctly is fiddly and easy to get wrong, especially around re-fetching and request de-duplication. TanStack Query's `useSuspenseQuery` already does this and plugs straight into Suspense, so almost no real app hand-rolls the throwing mechanism.

  3. 03If a component calls `useSuspenseQuery` and the request fails, what happens to the Suspense fallback?

    Nothing related to the fallback. A failed request throws the error itself rather than a pending promise, so Suspense never sees it; the failure has to be caught by an error boundary placed around the component, which is a separate mechanism from Suspense.

  4. 04What happens when two sibling components under the same Suspense boundary are both fetching data?

    The boundary shows its fallback until both are ready. React does not reveal one sibling early and leave the other suspended; the whole subtree under that boundary appears together once every suspending component inside it has resolved.

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