Skip to content
Tutorials Center
My learning

Topics

Lesson 27 of 38 ยท Suspense and Prefetching

Suspense Queries

Use useSuspenseQuery and useSuspenseQueries with React Suspense: no isPending checks, guaranteed data, fallbacks, nested boundaries and how to avoid request waterfalls.

So far every component checked isPending and isError before it could use data. That is a lot of repeated if statements, and TypeScript users know the annoyance: data is T | undefined until you narrow it. React Suspense offers another model. A component that is not ready "suspends", and the nearest <Suspense fallback={...}> above it shows a loading UI instead. Errors travel to the nearest error boundary.

TanStack Query v5 provides first-class hooks for this: useSuspenseQuery, useSuspenseInfiniteQuery and useSuspenseQueries. This lesson explains how they differ from useQuery and how to place boundaries well.

What changes

JSX
function Profile({ id }) {
  const { data } = useSuspenseQuery({
    queryKey: ["user", id],
    queryFn: () => fetchUser(id),
  });
  return <h2>{data.name}</h2>;   // data is always defined here
}

<Suspense fallback={<p>Loading profile...</p>}>
  <Profile id={7} />
</Suspense>

The differences from useQuery:

  • data is never undefined. The component only renders once data exists. In TypeScript the type is T, not T | undefined.
  • No isPending or isError. Loading is the fallback; errors are thrown to the error boundary.
  • No enabled option and no placeholderData. The query always runs, because a component cannot "wait" for a condition. For a dependent query, render a child component only when the condition holds.
  • Errors are thrown when a refetch fails and there is no data, or always with throwOnError-style semantics. If cached data exists and a background refetch fails, the old data is kept and no error is thrown unless you use an error boundary reset.

In v4 the same feature was useQuery({ suspense: true }). v5 replaced that flag with dedicated hooks so the types can promise that data exists. If you find suspense: true in a tutorial, it targets an older version.

A first Suspense example

useSuspenseQuery with a fallback

The profile shows first (0.9 s), then the posts (1.4 s) under their own inner fallback. Switching to a user you already visited is instant, because the data is cached.

Boundary placement

A <Suspense> boundary shows its fallback while any descendant suspends. The placement decides the user experience:

  • One boundary at the top: the whole page is replaced by one spinner. Simple, but it hides content that is already ready.
  • Boundaries around independent sections: each part appears when its data arrives. This is usually best: header first, then main content, then side widgets.
  • A boundary per list item: too many spinners looks noisy.

Match boundaries to how the page should reveal itself, not to components one-to-one.

flowchart TD
  A["Suspense: page skeleton"] --> B["Header (no data)"]
  A --> C["Suspense: profile card"]
  A --> D["Suspense: feed"]
  C --> E["Profile (suspends)"]
  D --> F["Feed (suspends)"]

Each boundary owns one independent area, so a slow feed never blocks the profile card.

The waterfall trap

Suspense changes when a query starts. A suspending component stops rendering at the first useSuspenseQuery that has no data, so code after it, and its children, do not run until the data arrives. If a parent fetches and then renders a child that fetches, the second request starts only after the first finishes, a waterfall:

JSX
function Page() {
  const { data: user } = useSuspenseQuery(userOptions(7)); // request 1 ... waits
  return <Posts userId={user.id} />;                        // request 2 only starts after
}

Two cures:

  1. Fetch in parallel with useSuspenseQueries when the requests do not depend on each other. All queries start together, and the component waits for all of them.
  2. Prefetch requests that you can start early (in an event handler, a route loader or the parent), so the child finds the data in the cache. Prefetching is the topic of Prefetching and Initial Data.
Parallel with useSuspenseQueries

The page appears after about 0.8 s, not 2.4 s. Three separate useSuspenseQuery calls in a row inside one component would suspend at the first one and run sequentially, which is exactly the waterfall to avoid.

Keeping the UI stable while a key changes

When a key changes (a new id), the component suspends again and the fallback replaces the content. To keep the old UI visible while the new data loads, wrap the state change in React.startTransition (or use useTransition):

JSX
const [isPending, startTransition] = React.useTransition();
<button onClick={() => startTransition(() => setId(n))}>User {n}</button>

React then keeps showing the old UI (dimmed with isPending) until the new one is ready. This is the Suspense counterpart of keepPreviousData.

When not to use Suspense

Suspense queries are great when the page is "all or nothing" per section. Prefer useQuery when a component must render before its data is ready (a search box that shows results later), when a query needs enabled, or when you want placeholderData. You can mix both in one app.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What type guarantee does useSuspenseQuery give about data?

    The component suspends until data exists, so the code after the hook can rely on it.
  2. 2. How are errors from useSuspenseQuery handled?

    There is no isError flag; wrap the component in an error boundary.
  3. 3. Why do three useSuspenseQuery calls in one component cause a waterfall?

    A suspending component stops at the first pending hook, so later hooks start only after. useSuspenseQueries starts all queries together.
  4. 4. How do you keep the old UI visible while a new key suspends?

    A transition tells React to keep showing the current UI instead of the fallback until the new content is ready.

Summary

  • useSuspenseQuery never returns undefined data and has no isPending or isError; it needs a Suspense boundary and an error boundary.
  • It has no enabled or placeholderData; use useQuery for those cases.
  • Place boundaries around independent sections to reveal the page progressively.
  • Avoid waterfalls with useSuspenseQueries or prefetching.
  • Use startTransition to keep old content visible while a new key loads.

Next: Error Boundaries and Resetting