Sub topic 11
Suspense on the Server: Streaming and Selective Hydration
This chapter assumes you know how React.lazy and Suspense work in the browser, including fallbacks and error boundaries. It also assumes you have seen server-side rendering (SSR), where the server turns components into HTML before the browser runs any JavaScript. You need Node.js and a bundler that can compile JSX.
The problem with classic SSR
Before React 18, server rendering was all or nothing. The server had to finish every step before the browser saw any of the result:
- Fetch all the data for the page.
- Render the whole page to an HTML string and send it.
- Download the JavaScript for the whole page.
- Hydrate the whole page.
Hydration is the step where React attaches event handlers to server-made HTML and makes it interactive. In the old model, a single slow component blocked everything after it. The browser could not show HTML until the slowest query finished. It could not hydrate any part of the page until all of the JavaScript had loaded. Hydration also ran in one block, so a heavy component made the whole page unresponsive.
Suspense fixes both ends. Streaming lets the server send HTML in pieces. Selective hydration lets the browser hydrate the pieces independently. Both use the Suspense boundaries you already write.
Streaming HTML
On the server, a Suspense boundary marks a place where the HTML can arrive later. When a component inside a boundary suspends, React does not wait. It sends the fallback in that spot and continues with the rest of the page. The first chunk of HTML is called the shell. It contains everything outside the suspended boundaries, plus the fallbacks.
When the suspended work finishes, React streams more HTML and a tiny inline script. The script moves the real content into the place held by the fallback. This works without your application JavaScript, so the content appears even before hydration.
A streaming server
React offers two streaming functions for the server. renderToPipeableStream is for Node.js streams. renderToReadableStream is for runtimes that use Web streams, such as edge workers and Deno. The example below uses the Node version.
The app renders the full document, including <html>, so that React controls the whole page:
// App.jsx
import { lazy, Suspense } from 'react';
const Comments = lazy(() => import('./Comments.jsx'));
export default function App() {
return (
<html lang="en">
<head>
<meta charSet="utf-8" />
<title>Post</title>
</head>
<body>
<h1>My post</h1>
<article>The article text renders immediately.</article>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</body>
</html>
);
}// Comments.jsx
export default function Comments() {
return (
<ul>
<li>First comment</li>
<li>Second comment</li>
</ul>
);
}The server hands the app to renderToPipeableStream and pipes the result into the HTTP response:
// server.jsx
import { createServer } from 'node:http';
import { renderToPipeableStream } from 'react-dom/server';
import App from './App.jsx';
createServer((req, res) => {
let didError = false;
const { pipe, abort } = renderToPipeableStream(<App />, {
bootstrapScripts: ['/client.js'],
onShellReady() {
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
pipe(res);
},
onShellError(error) {
console.error('Shell failed:', error);
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html; charset=utf-8');
res.end('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
console.error(error);
},
});
setTimeout(abort, 10000);
}).listen(3000);The options do the following:
bootstrapScriptsadds the script tags that load your client bundle.onShellReadyfires when the shell is complete. You start piping here, so the browser gets HTML as early as possible.onShellErrorfires when the shell itself cannot render. No HTML has been sent, so you can still return a clean error page.onErrorfires for every error, including errors inside Suspense boundaries.abortstops waiting for pending boundaries. Without a timeout, a hung promise keeps the response open. After an abort, React sends the unfinished boundaries to the client to render there instead.
Choosing when to start sending
onShellReady is not the only moment you can start piping. React exposes a second callback, and the choice depends on who is reading the page.
| Callback | Fires when | Use it for | Effect |
|---|---|---|---|
| `onShellReady` | The shell is complete, with fallbacks for pending boundaries | Browsers used by people | Fastest first paint, content streams in later |
| `onAllReady` | Every boundary has finished | Crawlers, static generation, email | One complete document, no fallbacks in the output |
A common pattern is to check the user agent. Bots wait for onAllReady, and browsers start at onShellReady.
Hydrating on the client
The browser entry point calls hydrateRoot. Because the server rendered the whole document, the client hydrates document:
// client.jsx
import { hydrateRoot } from 'react-dom/client';
import App from './App.jsx';
hydrateRoot(document, <App />);The client must render the same tree that the server did. If the output differs, React reports a hydration mismatch. In React 19, it recovers by rendering the affected part on the client. Mismatches cost performance and can show wrong content, so treat them as bugs.
Selective hydration
Suspense boundaries also divide the hydration work. Each boundary hydrates on its own, which gives three behaviors:
- Hydration does not block on a boundary that is not ready. If the code for
Commentsis still downloading, React hydrates the rest of the page and leaves the comments as plain HTML. The boundary's chunk can arrive later. - Hydration yields to the browser. React splits the work into small slices, so a large boundary does not freeze the page.
- User input sets the priority. If the user clicks inside a boundary that has not hydrated, React hydrates that boundary first. For discrete events such as clicks, React replays the event once the boundary is ready. Hovering and other continuous events raise the priority but are not replayed.
This is where React.lazy matters for server rendering. The server sends HTML for Comments, but the client still needs its JavaScript to hydrate. If Comments were imported statically, its code would be in the main bundle, and hydration could not start until the whole bundle arrived. With lazy, the boundary hydrates when its own chunk arrives, and nothing else waits.
What the user sees
Walk through the example on a slow connection:
- The browser receives the shell. It shows the heading, the article, and "Loading comments...".
- The server finishes the
Commentsrender and streams its HTML. The swap script replaces the fallback with the list. The user sees comments even though no JavaScript has run. client.jsloads and hydrates the shell. The comments chunk is still in flight, so that boundary stays inert.- The chunk arrives and the boundary hydrates. The comments are interactive.
On the client, the lazy component suspends while its chunk loads. During hydration, React keeps the server-rendered HTML in place instead of replacing it with the fallback. A visible, server-made boundary never flashes back to a loading state.
Suspense for data on the server
Components that read data with use suspend on the server in the same way as lazy components. Any Suspense-compatible data source streams.
Data brings a new requirement. The client must receive the same data the server used, or it would fetch it again and might render different output. Doing this by hand means serializing resolved values into the HTML and feeding them to the client render. This is hard to get right. Frameworks that integrate Suspense with routing and data loading, such as Next.js with the App Router, handle it for you. If you build your own server setup, start with lazy components, which do not carry data across the boundary.
Errors in a streamed response
An error means different things depending on where it happens:
- Inside the shell:
onShellErrorfires. Nothing has been sent, so you can return a 500 page. - Inside a Suspense boundary:
onErrorfires, but the response continues. React sends the fallback and tells the client to render the boundary itself. The client tries again. If it fails again, the nearest error boundary handles it, so keep one around your Suspense boundaries as in the browser-only chapters.
The status code is the main gotcha. HTTP sends the status before the body. After pipe(res) starts, you cannot change it. In the example above, errors that happen before the shell is ready can still set a 500. Errors in later boundaries cannot, and the user gets a 200 with a client-rendered section.
Common pitfalls
- Buffering middleware. Compression, reverse proxies, and some CDNs hold back output until the response ends. That defeats streaming. Check that your stack flushes chunks, and with compression make sure it flushes between chunks.
- A boundary with no fallback structure. Suspense boundaries that wrap the whole page make the shell empty. Put boundaries around slow sections, as covered in the placement chapter, so the shell has useful content.
- Effects.
useEffectdoes not run on the server. Content that depends on effects, such aswindowchecks, appears only after hydration and can cause mismatches if you read browser values during render. - Unstable IDs. Do not generate IDs with
Math.random()or counters. UseuseId, which gives the same value on server and client. - Slow shell. Streaming helps only if the shell is fast. Work outside any Suspense boundary still blocks
onShellReady. - Missing timeout. A promise that never settles keeps the response open. Always call
abortafter a deadline.
Summary of the model
- A Suspense boundary on the server is a point where HTML can arrive later.
- The shell is the first chunk. It holds everything outside pending boundaries, plus their fallbacks.
- Later chunks carry the real HTML and a small script that swaps it in.
- On the client, each boundary hydrates independently. User interaction raises a boundary's priority.
- Lazy components give each boundary its own chunk, so hydration does not wait for unrelated code.
Exercise
A page imports its Comments component statically and wraps it in Suspense. The server streams the page. The user clicks a button inside the comments before client.js finishes loading. Explain why selective hydration helps less here than with React.lazy, and what you change to fix it.
Show answer
With a static import, the code for Comments is part of the main bundle. No separate chunk exists for the boundary, so the boundary cannot hydrate until the whole bundle has loaded, which is the same moment the rest of the page can hydrate. Streaming still delivers the HTML early, but hydration gains nothing from the boundary. Changing the import to const Comments = lazy(() => import('./Comments.jsx')) puts the code in its own chunk. The shell can then hydrate as soon as the main bundle arrives. The comments hydrate when their chunk arrives, or sooner if the user clicks inside them and raises that boundary's priority.
Exercise
Your server calls pipe(res) inside onShellReady. A component inside a Suspense boundary later throws an error. What does the client receive, and can you still return a 500 status for that request?
Show answer
The client receives the fallback in the shell, and React tells it to render that boundary on the client. If the client render succeeds, the section appears normally. If it fails, the nearest error boundary handles it. You cannot return a 500 for that error. The status code was sent with the shell, before the error happened. To report the failure, record it in onError. You can set a 500 only for errors that occur before onShellReady fires.