Sub topic 11
Suspense on the Server: Streaming and Selective Hydration
This chapter assumes you know React.lazy, Suspense boundaries, and the basics of rendering a React app to HTML on a server. The earlier chapters cover lazy loading and fallbacks in the browser. Here the same boundaries also control how the server sends HTML and how the browser makes it interactive.
The problem with all-or-nothing server rendering
Without Suspense, server rendering has two all-or-nothing steps:
- The server must render the whole page before it sends any HTML. One slow component delays everything.
- The browser must download all the JavaScript and hydrate the whole page before any part of it responds to clicks. Hydration means attaching event handlers to server-made HTML.
Suspense boundaries break both steps into pieces.
Streaming HTML
renderToPipeableStream sends HTML in pieces. When a component inside a Suspense boundary suspends, React sends the page without it and puts the boundary's fallback in its place. This first piece is called the shell. When the suspended content is ready, React streams the real HTML. It arrives with a small inline script that swaps it in for the fallback. This works without any client JavaScript.
A minimal streaming server
This Express server streams the page. App must render the full <html> document, including the <body>.
import express from 'express';
import { createElement } from 'react';
import { renderToPipeableStream } from 'react-dom/server';
import App from './App.js';
const app = express();
app.use(express.static('public'));
app.get('/', (req, res) => {
let didError = false;
const { pipe } = renderToPipeableStream(createElement(App), {
bootstrapScripts: ['/client.js'],
onShellReady() {
res.statusCode = didError ? 500 : 200;
res.setHeader('Content-Type', 'text/html');
pipe(res);
},
onShellError() {
res.statusCode = 500;
res.send('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
console.error(error);
},
});
});
app.listen(3000);The callbacks do different jobs:
onShellReadyfires when everything outside the suspended boundaries is rendered. This is the moment to start sending.onShellErrorfires if the shell itself fails. No HTML has been sent yet, so you can still return a proper error page.onErrorfires for every error, including errors inside boundaries. A boundary that fails on the server falls back to its fallback, and React then tries to render it on the client.
The status code is fixed once you start sending. An error inside a later boundary cannot change a 200 to a 500.
Hydrating on the client
The browser entry point uses hydrateRoot, not createRoot:
import { hydrateRoot } from 'react-dom/client';
import App from './App.js';
hydrateRoot(document, <App />);The rendered tree must match the server HTML. A mismatch, such as output that depends on Date.now() or window, produces hydration warnings and can force the client to re-render.
Selective hydration
Each Suspense boundary is also a hydration unit. React hydrates them separately, and a boundary whose code or HTML has not arrived yet does not block the others.
If you use React.lazy for a component inside a boundary, the page does not wait for that chunk before it hydrates the rest. React hydrates the other parts first and hydrates the lazy part when its code loads.
If the user clicks inside a boundary that is not hydrated yet, React raises that boundary's priority. It hydrates the boundary first and then replays the click. The user's click is not lost.
For this reason, wrap the heavy or slow parts of the page, such as a comments section or a chart panel, in their own boundaries. The boundary placement advice from earlier still applies. One big boundary around the whole app gives you one hydration unit and one fallback.
Gotchas
renderToStringdoes not stream. A component that suspends renders its fallback, and the client renders the real content later. UserenderToPipeableStream(Node) orrenderToReadableStream(web streams runtimes) to get streaming.- Streamed content shifts the layout when it replaces a fallback. Give fallbacks the same dimensions as the final content.
- Crawlers and clients that do not run scripts may only see the shell. For content that must be indexed, make sure it is ready before
onShellReady. In React's API,onAllReadywaits for everything, so some setups use it for bots. - Server rendering gives you HTML sooner, but you still ship the JavaScript. Code splitting remains useful.
Exercise
A user clicks a button inside a Suspense boundary whose JavaScript has loaded but which has not been hydrated yet. What does React do, and why does this depend on Suspense boundaries?
Show answer
React raises that boundary's hydration priority, hydrates it ahead of the other pending boundaries, and then replays the click event. This is possible because each Suspense boundary is an independent hydration unit. Without boundaries, the whole page would hydrate as one piece.
Exercise
In the streaming server above, an error is thrown inside a component wrapped in a Suspense boundary after the shell has been sent. Can the server change the response status to 500, and what happens to that boundary?
Show answer
No. The status code and headers were sent with the shell, so the response stays at 200 (or whatever onShellReady chose). React shows the boundary's fallback and tries to render the content on the client instead.