Suspense and use

Waiting declaratively, and the fetching patterns behind it.

Builds on Transitions.

Every component that loads data has to answer the same question: what do I show while I wait? The effects chapter answered it the manual way, with useEffect, a loading flag and an early return <Spinner /> in each component. That works, but the waiting logic lives in every component separately, and the screen fills with spinners that appear and disappear on their own schedules.

Suspense moves that question up the tree. A component that isn't ready says so, and the nearest <Suspense> boundary above it decides what to show. This chapter covers what "isn't ready" means mechanically, how boundaries reveal, how use(promise) plugs data into it, why the promise must be cached, lazy() for code, and the data-fetching patterns that decide whether your page loads in 400 ms or 1.2 seconds.

The problem: spinners and waterfalls#

Here's a profile page written with effects. Profile loads the user, and only once it has the user does it render ReadingList, which then loads the books.

Fetching in effects

Watch the timestamps. Each request starts only after the previous one finished.

import { useEffect, useState } from "react";
import { fakeFetch } from "guide-tools";

const t0 = performance.now();
const since = () => Math.round(performance.now() - t0);

type User = { id: number; name: string };
type Book = { id: number; title: string };

function ReadingList() {
  const [books, setBooks] = useState<Book[] | null>(null);
  useEffect(() => {
    console.log(`GET /books starts at ${since()} ms`);
    fakeFetch("/books").then((b) => setBooks(b as Book[]));
  }, []);
  if (!books) return <p>Loading books...</p>;
  return (
    <>
      <p>Books arrived at {since()} ms</p>
      <ul>
        {books.slice(0, 3).map((b) => (
          <li key={b.id}>{b.title}</li>
        ))}
      </ul>
    </>
  );
}

export default function Profile() {
  const [user, setUser] = useState<User | null>(null);
  useEffect(() => {
    console.log(`GET /users/1 starts at ${since()} ms`);
    fakeFetch("/users/1").then((u) => setUser(u as User));
  }, []);
  if (!user) return <p>Loading user...</p>;
  return (
    <>
      <h3>{user.name}'s reading list</h3>
      <ReadingList />
    </>
  );
}

Two problems are tangled together here. The UI problem: each component owns a loading state, so loading indicators pop in and out piece by piece and there's no single place to say "show one skeleton for this whole area". The network problem: ReadingList can't start its request until it renders, and it can't render until Profile has its data. That chain is a waterfall, and it's the most common performance bug in client-rendered React. Suspense solves the first problem directly. It doesn't solve the second by itself, but it gives you the tools to.

What suspending means#

When a component reads something that isn't ready yet, it suspends: it tells React "I can't produce output right now". Mechanically, during the render phase React stops working on that component, walks up the tree to the nearest <Suspense> boundary, and renders that boundary's fallback instead of its children. It also subscribes to the thing being waited on. When that settles, React schedules a retry and renders the children again.

Here's the idea as a sketch, written in the toy's style. Real React does this inside its work loop, but the shape is the same:

function renderWithSuspense(boundary, children) {
  try {
    return render(children); // may hit a component that isn't ready
  } catch (thrown) {
    if (isThenable(thrown)) {
      thrown.then(() => scheduleRetry(boundary)); // try again later
      return render(boundary.fallback); // show the fallback meanwhile
    }
    throw thrown; // a real error: that's an error boundary's job
  }
}

Three consequences follow from that design, and each one shows up later in the chapter:

  • The whole boundary waits as a unit. If any child suspends, everything inside that boundary shows the fallback, and it all appears together when ready.
  • A component that suspends before it ever mounted keeps no state. React retries the render from scratch. Anything created during that render (including a promise) is created again.
  • Suspense only knows about things that suspend. Data fetched in an effect or event handler doesn't suspend anything. The docs list what does: lazy-loaded code (lazy), a promise read with use, stylesheets with a precedence, large boundaries while server-rendered HTML streams in, and (when a <ViewTransition> animates the reveal) fonts and images.

You never throw promises yourself. Older libraries did, but it was never a public API. The public way to suspend on data is use.

use(promise) React 19#

use reads the value of a promise. If the promise has resolved, use returns the value synchronously. If it's pending, the component suspends. If it rejected, use throws the error, and the nearest error boundary catches it.

use is not quite a hook: unlike hooks, it can be called inside if statements and loops (more on the limits of that below). It can also read context, as use(MyContext), which the context chapter covers. One more rule: you can't wrap it in try/catch, because suspending works by interrupting the render. Errors go to error boundaries.

Here's the reading list loading through Suspense. The fetch lives in a tiny cache module, and the component just reads.

Reading list: load books with use and Suspense
import { Suspense, use } from "react";
import { fetchCached } from "./data";

type Book = { id: number; title: string; author: string };

function BookList() {
  const books = use(fetchCached<Book[]>("/books"));
  return (
    <ul>
      {books.map((b) => (
        <li key={b.id}>
          {b.title} <small>by {b.author}</small>
        </li>
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <>
      <h3>Reading list</h3>
      <Suspense fallback={<p>Loading books...</p>}>
        <BookList />
      </Suspense>
    </>
  );
}

BookList has no loading state, no effect and no null check. It's written as if the data were already there, and the boundary handles the waiting. That's the real win: loading UI is decided by where you put boundaries, not by every component separately.

Why the promise must be cached#

Here's the version everyone writes first, with the cache removed. Mount it and watch the console.

The uncached promise trap
import { Suspense, use, useState } from "react";
import { fakeFetch } from "guide-tools";

let requests = 0;
function fetchBooks() {
  requests += 1;
  console.log(`request #${requests} for /books`);
  return fakeFetch("/books") as Promise<{ id: number; title: string }[]>;
}

function BookList() {
  const books = use(fetchBooks()); // a new promise on every render
  return <p>{books.length} books</p>;
}

export default function App() {
  const [show, setShow] = useState(false);
  return (
    <>
      <button onClick={() => setShow(!show)}>{show ? "Unmount" : "Mount the broken list"}</button>
      {show ? (
        <Suspense fallback={<p>Loading books...</p>}>
          <BookList />
        </Suspense>
      ) : null}
    </>
  );
}
Nothing logged yet.

It never finishes. The render calls fetchBooks(), gets a new promise, suspends on it, and shows the fallback. 400 ms later the promise resolves and React retries BookList from scratch, because a component that suspended before mounting has no state to keep. The retry calls fetchBooks() again, which makes a new pending promise, which suspends again. A request every 400 ms, forever. (If you see the development error "A component was suspended by an uncached promise", that's React catching the same mistake on a faster path.)

The rule: the promise passed to use must be the same object across renders. Create it outside the suspending component (in a cache, a loader, an event handler or a parent's state) so the retry gets the already-resolved promise and use returns its value immediately. The same trap catches use(fetchCached(url).then(r => r.json())): .then returns a new promise on every call, even if the inner one is cached.

In practice you rarely write the cache yourself. Frameworks (Server Components pass promises down from the server) and data libraries (server state: TanStack Query's useSuspenseQuery, SWR's suspense option) own the caching, deduplication and invalidation, which is the genuinely hard part.

The conditional use() warning React 19.3#

use may be called conditionally, but the condition must not be about the promise itself. A common clever trick reads the promise's status to skip use when the value is already there:

// Don't do this.
function BookList({ promise }: { promise: Promise<Book[]> & { status?: string; value?: Book[] } }) {
  const books = promise.status === "fulfilled" ? promise.value! : use(promise);
  // ...
}

The first render suspends through use. The retry takes the other branch and never calls use at all, so React can't track the promise it was waiting on. React 19.3 adds a development warning for this: "This library called use() to suspend in a previous render but did not call use() when it finished." Always pass the promise to use and let React decide whether to suspend. Conditions about whether you need the data (if (showDetails) use(detailsPromise)) are fine.

Boundaries, fallbacks and reveal order#

Where you put boundaries is a design decision. One boundary around the whole page gives you one loading state and everything appears at once. A boundary per widget gives you a page that fills in piece by piece. Nesting gives you a sequence: first the shell, then the details.

Nested Suspense boundaries reveal from the outside in
The tree<Suspense fallback={<BigSpinner/>}><Biography /><Suspense fallback={<AlbumsGlimmer/>}><Panel><Albums /></Panel>clay = still waiting for dataThe screenBigSpinner
Step 1 of 5

First render. Biography and Albums both suspend. The outer boundary is the nearest one above Biography, so its fallback, BigSpinner, covers the whole area. The inner boundary hasn't been revealed, so it shows nothing of its own yet.

Nested boundaries with different speeds

The author loads in 600 ms and the books in 1500 ms. Try swapping the delays in App.tsx and press Reload.

import { Suspense, use, useState } from "react";
import { fetchCached, clearCache } from "./data";

const AUTHOR_DELAY = 600;
const BOOKS_DELAY = 1500;

function Author() {
  const user = use(fetchCached<{ name: string }>("/users/1", AUTHOR_DELAY));
  return <h3>{user.name}'s shelf</h3>;
}

function Books() {
  const books = use(fetchCached<{ id: number; title: string }[]>("/books", BOOKS_DELAY));
  return (
    <ul>
      {books.slice(0, 4).map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [run, setRun] = useState(0);
  return (
    <>
      <button
        onClick={() => {
          clearCache();
          setRun((r) => r + 1);
        }}
      >
        Reload
      </button>
      <Suspense key={run} fallback={<p>Loading the page...</p>}>
        <Author />
        <Suspense fallback={<p>Loading books...</p>}>
          <Books />
        </Suspense>
      </Suspense>
    </>
  );
}

Notice that both requests start right away, even though Books sits inside a boundary that waits for Author. When Author suspends, React commits the outer fallback immediately and then keeps rendering the rest of the suspended tree in the background (React calls this pre-warming) to discover what else it will need, so Books starts its request too. That's why nesting boundaries doesn't create a waterfall here; nesting components that only render after a parent's data arrives does, as in the effects example.

Two timing details matter for how this feels:

  • Throttled reveals. React won't switch boundaries between fallback and content more often than once every 300 ms. Content that becomes ready less than 300 ms after the last switch waits until the window ends, and everything ready by then is revealed in the same commit, so a page doesn't flicker through five states in half a second.
  • Batched reveals during streaming. React 19.2 Before 19.2, server-streamed HTML replaced fallbacks the moment each boundary arrived, which differed from client rendering. Since 19.2, React batches reveals of server-rendered boundaries for a short time too, so both paths behave the same. React stops batching if the page is getting close to the 2.5 s "good" LCP threshold. SSR and hydration covers streaming.

Transitions keep revealed content on screen#

Once a boundary has shown content, what happens if an update makes it suspend again? With a normal update, the content is swapped back for the fallback: the list you were reading vanishes into "Loading...". If the update is a transition, React keeps showing the old content until the new content is ready. Here's the reading list again, filtered by tag through the API.

Reading list: switching tags with and without a transition
import { Suspense, use, useState, useTransition } from "react";
import { fetchCached } from "./data";

type Book = { id: number; title: string };

function BookList({ tag }: { tag: string }) {
  const books = use(fetchCached<Book[]>(`/books?q=${tag}`));
  return (
    <ul>
      {books.map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  const [tag, setTag] = useState("craft");
  const [useTx, setUseTx] = useState(true);
  const [isPending, startTransition] = useTransition();

  function choose(next: string) {
    if (useTx) startTransition(() => setTag(next));
    else setTag(next);
  }

  return (
    <>
      <label>
        <input type="checkbox" checked={useTx} onChange={(e) => setUseTx(e.target.checked)} /> Use a transition
      </label>
      <p>
        {["craft", "systems", "fundamentals", "teams"].map((t) => (
          <button key={t} onClick={() => choose(t)} disabled={t === tag}>
            {t}
          </button>
        ))}
      </p>
      <div style={{ opacity: isPending ? 0.5 : 1 }}>
        <Suspense fallback={<p>Loading books...</p>}>
          <BookList tag={tag} />
        </Suspense>
      </div>
    </>
  );
}

With the transition, clicking a tag dims the current list until the new one is ready. Without it, the list disappears into the fallback for each new tag. (Tags you've already loaded are cached, so they switch instantly either way.)

Sometimes you want the fallback, for example when navigating from one person's profile to another's, where showing the previous person's data would be wrong. Put a key on the boundary (<Suspense key={userId}>): a new key means a new boundary, which shows its fallback even inside a transition.

lazy(): suspending on code#

Data isn't the only thing worth waiting for. A big component, such as a chart library or an editor, doesn't need to be in the initial JavaScript bundle if most users never open it. lazy lets you load a component's code on first render, and it suspends while the code downloads:

import { lazy } from "react";

const StatsPanel = lazy(() => import("./StatsPanel")); // a separate chunk

The function you pass must return a promise of a module whose default export is a component, which is exactly what a dynamic import() gives you. Bundlers like Vite, webpack and Turbopack see the dynamic import and split that module into its own file. React calls the function the first time <StatsPanel /> renders, suspends until it resolves, and caches the result.

Code splitting with lazy

The sandbox doesn't download chunks over a network, so sleep(1000) stands in for the download.

import { lazy, Suspense, useState } from "react";
import { sleep } from "guide-tools";

// Declared at module level, so it's created once.
const StatsPanel = lazy(() => sleep(1000).then(() => import("./StatsPanel")));

export default function App() {
  const [open, setOpen] = useState(false);
  return (
    <>
      <button onClick={() => setOpen(!open)}>{open ? "Hide" : "Show"} reading stats</button>
      {open ? (
        <Suspense fallback={<p>Loading the stats code...</p>}>
          <StatsPanel />
        </Suspense>
      ) : null}
    </>
  );
}

Open it, close it, open it again: the second time is instant because lazy cached the loaded component. Two rules: declare lazy components at module level (inside a component, every render creates a new component type and remounts it), and split at boundaries users actually cross, like routes, tabs, dialogs and heavy widgets. Splitting tiny components costs more in requests than it saves. Big UI comes back to bundle strategy.

Data-fetching patterns#

Suspense tells React how to wait. It says nothing about when requests start, and that's what decides how fast the page is. There are three patterns, and interviewers love asking you to compare them.

Three ways to load the same three things
0 ms400 ms800 ms1200 msGET /users/1GET /booksGET /books/1authorlistdetailContent appearsauthorlistdetail
Step 1 of 3

Fetch-on-render. Each component starts its own request when it renders, and a child only renders after its parent's data arrived. Three 400 ms requests take 1.2 seconds, because each one waits for the last. This is the waterfall.

Fetch-on-render. Each component starts its request when it renders. Simple and colocated, but a child can't start until its parent has rendered, and with Suspense a component deeper in the tree doesn't even render until the components above it stop suspending. Every level of nesting adds a round trip. That's the waterfall, and it happens with effects and with naive use alike.

Fetch-then-render. Start everything up front, await Promise.all, then render. No waterfall, but nothing shows until the slowest request is done.

Render-as-you-fetch. Start every request as early as possible (in the event handler that triggers navigation, a route loader or a parent), pass the promises down, and let each component use its own promise inside its own boundary. Requests run in parallel and each part of the screen appears when its data does. This is what Suspense was designed for, and it's what frameworks do for you: route loaders, Server Components that start fetches on the server and stream promises to the client, and prefetch APIs.

Run both versions of the same screen below and compare the arrival times.

Waterfall versus render-as-you-fetch
import { Suspense, use, useState } from "react";
import { fakeFetch } from "guide-tools";

type Timed = { data: any; at: number };
let t0 = 0;
function timed(path: string): Promise<Timed> {
  return fakeFetch(path).then((data) => ({ data, at: Math.round(performance.now() - t0) }));
}

// ---- Fetch-on-render: each component starts its own request ----
const cache = new Map<string, Promise<Timed>>();
function onRender(path: string) {
  if (!cache.has(path)) cache.set(path, timed(path));
  return cache.get(path)!;
}

function AuthorW() {
  const { data, at } = use(onRender("/users/1"));
  return (
    <>
      <p>Author: {data.name} (arrived at {at} ms)</p>
      <ListW />
    </>
  );
}
function ListW() {
  const { data, at } = use(onRender("/books"));
  return (
    <>
      <p>List: {data.length} books (arrived at {at} ms)</p>
      <DetailW />
    </>
  );
}
function DetailW() {
  const { data, at } = use(onRender("/books/1"));
  return <p>Detail: {data.title} (arrived at {at} ms)</p>;
}

// ---- Render-as-you-fetch: start everything first, pass promises down ----
type Promises = { author: Promise<Timed>; list: Promise<Timed>; detail: Promise<Timed> };

function Section({ label, promise, show }: { label: string; promise: Promise<Timed>; show: (d: any) => string }) {
  const { data, at } = use(promise);
  return (
    <p>
      {label}: {show(data)} (arrived at {at} ms)
    </p>
  );
}

export default function App() {
  const [waterfallRun, setWaterfallRun] = useState(0);
  const [promises, setPromises] = useState<Promises | null>(null);

  function runWaterfall() {
    t0 = performance.now();
    cache.clear();
    setPromises(null);
    setWaterfallRun((r) => r + 1);
  }

  function runParallel() {
    t0 = performance.now();
    setWaterfallRun(0);
    // Start every request in the event handler, before rendering.
    setPromises({ author: timed("/users/1"), list: timed("/books"), detail: timed("/books/1") });
  }

  return (
    <>
      <button onClick={runWaterfall}>Run fetch-on-render</button>{" "}
      <button onClick={runParallel}>Run render-as-you-fetch</button>
      {waterfallRun > 0 ? (
        <Suspense key={waterfallRun} fallback={<p>Loading...</p>}>
          <AuthorW />
        </Suspense>
      ) : null}
      {promises ? (
        <>
          <Suspense fallback={<p>Author...</p>}>
            <Section label="Author" promise={promises.author} show={(d) => d.name} />
          </Suspense>
          <Suspense fallback={<p>List...</p>}>
            <Section label="List" promise={promises.list} show={(d) => `${d.length} books`} />
          </Suspense>
          <Suspense fallback={<p>Detail...</p>}>
            <Section label="Detail" promise={promises.detail} show={(d) => d.title} />
          </Suspense>
        </>
      ) : null}
    </>
  );
}

The waterfall's three requests arrive at roughly 400, 800 and 1200 ms. The render-as-you-fetch requests all arrive at about 400 ms. Same data, same components, a third of the wait.

Errors: Suspense and error boundaries together#

A rejected promise makes use throw, and the nearest error boundary catches it. In practice the two boundaries travel together: Suspense for "not yet", an error boundary for "failed". To retry, invalidate the cached promise and reset the error boundary, so the subtree renders again and creates a fresh request.

A failed load, with retry

The first request fails. Try again clears the cached promise and resets the boundary.

import { Suspense, use } from "react";
import { fakeFetch } from "guide-tools";
import { ErrorBoundary } from "./ErrorBoundary";

let attempt = 0;
let booksPromise: Promise<{ id: number; title: string }[]> | null = null;
function getBooks() {
  if (!booksPromise) {
    attempt += 1;
    booksPromise = fakeFetch("/books", { delay: 700, fail: attempt === 1 }) as Promise<{ id: number; title: string }[]>;
  }
  return booksPromise;
}

function BookList() {
  const books = use(getBooks());
  return <p>Loaded {books.length} books on attempt {attempt}.</p>;
}

export default function App() {
  return (
    <ErrorBoundary
      onReset={() => (booksPromise = null)}
      fallback={(error, reset) => (
        <div role="alert">
          <p>{error.message}</p>
          <button onClick={reset}>Try again</button>
        </div>
      )}
    >
      <Suspense fallback={<p>Loading books...</p>}>
        <BookList />
      </Suspense>
    </ErrorBoundary>
  );
}

Order matters. With the error boundary outside the Suspense boundary, a failure replaces the whole area, fallback included. Put the error boundary inside to keep surrounding content and only replace the failed part. And remember the cache: if you reset the boundary but keep the rejected promise cached, the retry reads the same rejection and fails again immediately.

Pitfalls#

Check your understanding#

Fix itLoading forever

This reading list never gets past "Loading books...". Fix it so the books appear, and so /books is requested exactly once. The checks wait for a title and count requests in requestLog.

import { Suspense, use } from "react";
import { fakeFetch } from "guide-tools";

type Book = { id: number; title: string };

function BookList() {
  const books = use(fakeFetch("/books") as Promise<Book[]>);
  return (
    <ul>
      {books.map((b) => (
        <li key={b.id}>{b.title}</li>
      ))}
    </ul>
  );
}

export default function App() {
  return (
    <Suspense fallback={<p>Loading books...</p>}>
      <BookList />
    </Suspense>
  );
}
PredictWhat appears when?

Header resolves after 300 ms, Feed after 1000 ms and Sidebar after 200 ms. Describe what the screen shows at 0 ms, 300 ms and 1000 ms.

<Suspense fallback={<PageSkeleton />}>
  <Header />
  <Sidebar />
  <Suspense fallback={<FeedSkeleton />}>
    <Feed />
  </Suspense>
</Suspense>
Quick checkDoes this suspend?

Which of these makes the nearest Suspense boundary show its fallback?

Quick checkTwo boundaries, close together

Two sibling Suspense boundaries show their fallbacks at 0 ms. Their data arrives at 100 ms and 200 ms. What does React do on the client?

Explain it out loudWaterfalls and how to avoid them

An interviewer asks: "What's a request waterfall in React, and how do Suspense and render-as-you-fetch help?"

Interview angle

Say it in 30 seconds

Suspense lets a component say it isn't ready, so the nearest boundary shows a fallback and React retries when the data or code arrives. You suspend on data with use(promise) and on code with lazy(). The promise has to be cached, because a component that suspended before mounting is retried from scratch, so a promise created in render loops forever. Everything in a boundary reveals together, nested boundaries reveal from the outside in, and transitions keep revealed content on screen. Suspense controls waiting, not when requests start: to avoid waterfalls, start requests early and pass promises down.

What does it mean for a component to suspend?

basic

Why must the promise passed to use() be cached? What happens if it isn't?

intermediate

Compare fetch-on-render, fetch-then-render and render-as-you-fetch.

senior

What happens when an already visible Suspense boundary suspends again?

intermediate

How does React decide when to reveal Suspense content?

senior

How does lazy() work, and where should you use it?

basic

How do you handle a failed load with Suspense?

intermediate

Recap#

  • A component suspends when it reads something that isn't ready. React shows the nearest <Suspense> fallback and retries when it settles. Only use on a promise, lazy and a few resource types suspend; effects don't.
  • use(promise) reads a promise, suspends while it's pending and throws to an error boundary if it rejects. The promise must be cached, because a component that suspended before mounting is retried from scratch. Since 19.3, React warns when use is skipped on the retry.
  • Everything inside a boundary reveals together, nested boundaries reveal outside-in, switches between fallback and content are throttled to one per 300 ms, and since 19.2 server-streamed boundaries are batched the same way. Transitions keep revealed content instead of falling back.
  • lazy(() => import(...)) splits code and suspends while it loads. Declare it at module level.
  • Fetch-on-render causes waterfalls. Render-as-you-fetch starts requests early and passes promises down, so requests overlap and sections appear independently.

Sources#