Next.jsMedium
What is Suspense and how does it work in Next.js?
<Suspense> is a React component that shows a fallback while its children are waiting for something, such as data or code. In Next.js it powers streaming: the server sends the fallback in the initial HTML, keeps rendering the suspended part, and streams the finished HTML into place when it is ready.
How a component suspends
- An async Server Component that
awaits data. - A Client Component calling
use(promise)on an unresolved promise. - A lazy-loaded component (
React.lazy,next/dynamic). - Suspense-enabled libraries such as
useSuspenseQuery.
In Next.js specifically
loading.tsxis shorthand for a<Suspense>boundary around a page.- Streaming: each boundary resolves independently and is streamed in order of completion, so time to first byte stays low.
- Partial Prerendering (Cache Components): everything outside
<Suspense>boundaries plus the fallbacks form the static shell; the content inside streams at request time. Next.js requires request-time work to be inside a boundary or cached. - Selective hydration: React hydrates the parts that have arrived and prioritizes the area the user interacts with.
Rules of thumb
- Place boundaries around independent, slow pieces, not around the whole page.
- Boundaries nest: the nearest one above a suspending component shows its fallback.
- Inside a transition (
startTransition, Link navigation), React keeps showing existing content instead of falling back again. Give a boundary akeyto force the fallback on change. - Suspense does not catch errors; pair it with
error.tsxorcatchError. - A component doing only synchronous work never suspends, even inside
<Suspense>.
Code example
tsx
1// app/movie/[id]/page.tsx2import { Suspense } from "react";34async function Reviews({ id }: { id: string }) {5 const reviews = await fetch(`https://api.example.com/movies/${id}/reviews`).then((r) => r.json());6 return <ul>{reviews.map((r: { id: string; text: string }) => <li key={r.id}>{r.text}</li>)}</ul>;7}89async function Cast({ id }: { id: string }) {10 const cast = await fetch(`https://api.example.com/movies/${id}/cast`).then((r) => r.json());11 return <p>{cast.map((c: { name: string }) => c.name).join(", ")}</p>;12}1314export default async function Movie({ params }: PageProps<"/movie/[id]">) {15 const { id } = await params;16 return (17 <main>18 <h1>Movie {id}</h1>19 {/* Two boundaries: whichever finishes first streams first */}20 <Suspense fallback={<p>Loading cast…</p>}>21 <Cast id={id} />22 </Suspense>23 <Suspense fallback={<p>Loading reviews…</p>}>24 <Reviews id={id} />25 </Suspense>26 </main>27 );28}
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 Next.js set.