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.lazycomponents loading their chunk.use(promise)reading an unresolved promise (React 19).- Suspense-enabled data libraries: TanStack Query's
useSuspenseQuery, SWR withsuspense: 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 akeyon 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";23const Comments = lazy(() => import("./comments"));45function fetchUser(id: string) {6 return fetch(`/api/users/${id}`).then((r) => r.json() as Promise<{ name: string; bio: string }>);7}89function Profile({ userPromise }: { userPromise: Promise<{ name: string; bio: string }> }) {10 const user = use(userPromise); // suspends until resolved11 return (12 <header>13 <h1>{user.name}</h1>14 <p>{user.bio}</p>15 </header>16 );17}1819// The promise must be created outside render (here: once per page load), not inside Profile20const userPromise = fetchUser("42");2122export 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.