Streaming, Suspense and hydration errors
Server-side rendering in React 18 can stream. Instead of waiting for the whole page, the server sends what's ready and fills in the slow parts as they arrive.
Server-side rendering in React 18 can stream. Instead of waiting for the whole page, the server sends what’s ready and fills in the slow parts as they arrive. It’s a real improvement. It also comes with the most confusing errors in React: hydration mismatches.
How streaming works
With renderToString, the server can’t send anything until every component, including the slowest data fetch, has finished. React 18’s renderToPipeableStream sends the page in pieces, split at Suspense boundaries:
function ProductPage({ productId }) {
return (
<>
<Header />
<ProductDetails />
<Suspense fallback={<ReviewsSkeleton />}>
<Reviews productId={productId} />
</Suspense>
</>
);
}
The header and product details go out immediately, with the skeleton in place of reviews. When the reviews are ready, React streams their HTML down the same response, plus a small inline script that swaps it into place. The user sees the page sooner, and the slow part doesn’t hold everything else back.
On the server (Node), it looks like this:
import { renderToPipeableStream } from 'react-dom/server';
function handler(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');
pipe(res);
},
onShellError() {
res.statusCode = 500;
res.setHeader('Content-Type', 'text/html');
res.end('<h1>Something went wrong</h1>');
},
onError(error) {
didError = true;
console.error(error);
},
});
setTimeout(() => abort(), 10_000);
}
The “shell” is everything outside of any Suspense boundary. onShellReady fires as soon as that’s rendered. If something fails inside a boundary, React sends the fallback for that part and tries again on the client. The abort timeout stops the stream from hanging forever if a data source never answers.
If you’re crawling for SEO or generating static HTML, use onAllReady instead, which waits for everything.
Hydration does the same in reverse
On the client, hydrateRoot attaches React to the HTML that’s already there. With Suspense boundaries, React 18 also hydrates in pieces. It can hydrate the header while reviews are still loading, and if the user clicks inside a part that isn’t hydrated yet, React hydrates that part first.
hydrateRoot(document.getElementById('root'), <App />, {
onRecoverableError(error) {
reportToMonitoring(error);
},
});
Add onRecoverableError. Hydration mismatches don’t crash the app, so without it they can be happening in production without anyone noticing.
The hydration errors
Hydration assumes the client’s first render produces exactly the same HTML as the server did. When it doesn’t, you get messages like:
Warning: Text content did not match. Server: “7/12/2024, 10:00:00 AM” Client: “12/07/2024, 15:30:00” Error: Text content does not match server-rendered HTML. Error: Hydration failed because the initial UI does not match what was rendered on the server.
React 18 then throws away the server HTML and renders that part on the client. If the mismatch happens outside any Suspense boundary, the whole root switches to client rendering, and you lose the benefit of SSR on that page.
The usual causes:
- Dates and times. The server formats in its own time zone and locale, the browser in the user’s.
- Browser-only values. window.innerWidth, localStorage, navigator.onLine, read during render.
- typeof window !== ‘undefined’ checks that render different markup on server and client.
- Random values. Math.random() or Date.now() in render.
- Invalid HTML. A inside a
. The browser’s parser “fixes” the server HTML, so the DOM React finds isn’t what it sent. React warns about this with validateDOMNesting.
- Browser extensions that inject elements into the page. Not your bug, but it shows up in your logs.
Fixing them
If a small piece of text is meant to differ, like a formatted timestamp, tell React to expect it:
function LastUpdated({ timestamp }) {
return (
<time dateTime={new Date(timestamp).toISOString()} suppressHydrationWarning>
{new Date(timestamp).toLocaleString()}
</time>
);
}
This only works one level deep, on the element’s own text. It’s not a way to silence a whole subtree.
If the client needs browser-only data, render the server version first and switch after hydration:
function useIsClient() {
const [isClient, setIsClient] = useState(false);
useEffect(() => {
setIsClient(true);
}, []);
return isClient;
}
function CartCount() {
const isClient = useIsClient();
if (!isClient) return <span>0</span>;
return <span>{localStorage.getItem('cartCount') ?? 0}</span>;
}
The first client render matches the server, then the effect triggers a second render with the real value. It costs one extra render, which is fine for small pieces like this.
For subscriptions to browser state, useSyncExternalStore takes a separate snapshot for the server:
function useOnline() {
return useSyncExternalStore(
subscribe,
() => navigator.onLine, // client
() => true, // server and hydration
);
}
React uses the third function during hydration too, so there’s no mismatch, and then switches to the real value.
Finding the real cause
React 18’s messages often don’t tell you which component caused the mismatch. What helps most is to run the page with JavaScript disabled, save the HTML, then compare it with the DOM after hydration. The difference usually points straight at a date, a window check or a bad nesting. Wrapping suspicious sections in their own Suspense boundaries also helps, because a mismatch then only falls back to client rendering for that section instead of the whole page.