Hydration
Hydration
(Note: This concept is also covered in the React DOM section, but we will explore it here strictly in the context of SSR architectures).
Hydration is the process where React takes a static HTML document generated by a server and makes it interactive by attaching JavaScript event listeners.
The Two-Pass Render
In an SSR application (like Next.js), rendering happens twice:
- Pass 1: The Server. The Node.js server executes your React components. It takes the resulting Virtual DOM, turns it into a giant string of HTML text, and sends it over the network to the browser.
- Pass 2: The Client (Hydration). The browser receives the HTML and paints it. Then, it downloads your React JavaScript bundle. React boots up in the browser and executes your components again. It builds a client-side Virtual DOM and compares it to the physical HTML that the server sent. It then attaches event listeners (like
onClick) to the physical DOM elements.
The “Uncanny Valley”
Because of this two-pass system, SSR applications suffer from a unique UX problem often called the “Uncanny Valley” of hydration.
If the server sends the HTML quickly, but the JavaScript bundle takes 3 seconds to download and parse (due to a slow 3G connection), there is a 3-second window where the user sees a perfectly styled, complete web page.
However, if they click a button, open a dropdown menu, or try to submit a form, nothing happens. The page is “dead” until hydration completes.
Progressive Hydration
To solve the Uncanny Valley problem, modern React (v18+) uses Selective Hydration combined with Suspense.
Instead of waiting for the entire application’s JavaScript to download before hydrating the whole page at once, React 18 can hydrate parts of the page independently.
If you wrap components in <Suspense>, React will:
- Show the server-rendered HTML for everything.
- Prioritize hydrating the parts of the page the user interacts with first. (e.g., If the user clicks the Sidebar before the Main Content JS has loaded, React will rush to hydrate the Sidebar first).
Interview Questions
Q: What is “Hydration” in React?
A: When a server sends fully rendered HTML to the browser (via SSR), the page looks complete but is completely static and non-interactive. Hydration is the process where React boots up on the client side, traverses the existing HTML, and attaches event listeners to breathe “life” and interactivity into it.