Sub topic 14
Selective hydration of Suspense boundaries
This chapter assumes you can render a page with renderToPipeableStream, attach it with hydrateRoot, and wrap slow parts of the tree in <Suspense>. It covers how React hydrates those boundaries independently.
The problem selective hydration solves
Without Suspense, hydration is all-or-nothing. React must download all the JavaScript for the page, then hydrate the whole tree in one pass. One heavy component, such as a comments widget, delays interactivity for everything, including the header and the article.
Selective hydration removes that dependency. Each Suspense boundary can hydrate on its own schedule, so the rest of the page becomes interactive without waiting for the slow part.
A page with one boundary
import { lazy, Suspense } from 'react';
const Comments = lazy(() => import('./Comments.js'));
export default function Page() {
return (
<main>
<h1>Article</h1>
<Suspense fallback={<p>Loading comments...</p>}>
<Comments />
</Suspense>
</main>
);
}Comments is loaded with lazy, so its code is in a separate JavaScript chunk. On the client, React hydrates <main> and the heading first. When it reaches the boundary and the chunk has not arrived, it leaves the server HTML for that section in place and keeps going. It hydrates the boundary later, when the code is ready.
What React does, step by step
- The server streams the shell, then the comments HTML as it becomes ready.
- The browser shows all of that HTML. It is visible but not yet interactive.
hydrateRoothydrates everything outside the pending boundary. The page is partly interactive.- When the
Commentschunk loads, React hydrates the boundary.
Hydration follows user input
React does not always hydrate boundaries in document order. If a user clicks inside a boundary that has not hydrated yet, React raises that boundary's priority and hydrates it first. It then replays the click so it is not lost. Discrete events such as clicks are replayed this way.
This means that a user who clicks a visible but not yet interactive section usually sees the expected result, with a short delay.
Gotchas
- The boundary must be a real
Suspenseboundary. Components outside any boundary hydrate together with their parent. - Code must be split, for example with
lazy. If the JavaScript is already in the main bundle, hydration still happens during the main pass, and you gain little. - Hydration inside a boundary can still hit mismatches. React then falls back to client rendering for that boundary, not the whole page. Chapter material on recoverable errors covers how to report this.
Exercise
A user clicks a button inside a Suspense boundary before that boundary has hydrated. What does React do?
Show answer
React raises the boundary's hydration priority, hydrates it ahead of other pending work, and replays the click once hydration finishes, so the click is not lost.