ReactMedium

What is Suspense?

<Suspense fallback={...}> displays a fallback UI while any component inside it is waiting for something: lazily loaded code (React.lazy), data read with use(promise) or a Suspense-enabled library, or server-rendered content still streaming. When everything inside is ready, React swaps the fallback for the content.

What can suspend

  • React.lazy components loading their chunk.
  • use(promise) reading an unresolved promise (React 19).
  • Suspense-enabled data libraries: TanStack Query's useSuspenseQuery, SWR with suspense: true, Relay, Apollo.
  • Async Server Components and streamed SSR in frameworks like Next.js.
  • React 19.3's use(browser()): a component that suspends during server rendering and renders only in the browser.

Behavior

  • The nearest <Suspense> boundary above a suspending component shows its fallback.
  • Nested boundaries reveal content progressively, from outer to inner.
  • Inside a transition (navigation, startTransition), React keeps showing existing content instead of falling back again; use a key on the boundary to force a reset.
  • On the server, fallbacks are sent first in the HTML stream and replaced as content resolves; React batches reveals to reduce flicker (19.2).
  • Suspense does not catch errors; combine with an error boundary.

Design tips

  • Place boundaries around independent regions, not around the whole app or every tiny component.
  • Use skeletons that match the final layout to avoid layout shift.
  • Start data requests early (in loaders or parents) so components do not fetch in a waterfall.

Code example

tsx
1import { lazy, Suspense, use } from "react";
2
3const Comments = lazy(() => import("./comments"));
4
5function fetchUser(id: string) {
6 return fetch(`/api/users/${id}`).then((r) => r.json() as Promise<{ name: string; bio: string }>);
7}
8
9function Profile({ userPromise }: { userPromise: Promise<{ name: string; bio: string }> }) {
10 const user = use(userPromise); // suspends until resolved
11 return (
12 <header>
13 <h1>{user.name}</h1>
14 <p>{user.bio}</p>
15 </header>
16 );
17}
18
19// The promise must be created outside render (here: once per page load), not inside Profile
20const userPromise = fetchUser("42");
21
22export function ProfilePage() {
23 return (
24 <main>
25 <Suspense fallback={<div className="skeleton h-16" />}>
26 <Profile userPromise={userPromise} />
27 <Suspense fallback={<p>Loading comments…</p>}>
28 <Comments />
29 </Suspense>
30 </Suspense>
31 </main>
32 );
33}

Practice this question

Open it in the study app to track progress, take notes, listen to the answer and work through the rest of the React set.

Open in study app