SSR and hydration

Render to HTML, stream it, and bring it to life.

Builds on Rendering strategies.

The previous chapter compared rendering strategies from a distance. This one gets its hands dirty. Server rendering in React comes down to two halves: a server half that turns a component tree into HTML, and a client half, hydration, that turns that HTML back into a live React app without throwing it away.

Both halves run in your browser in this chapter. react-dom/server and react-dom/static have browser builds, so every sandbox below renders to HTML, reads the stream chunk by chunk, writes it into the page and hydrates it, all in one place. The "server" is pretend; the APIs and the bytes they produce are the real ones.

The problem: HTML that can't do anything#

Server HTML is just markup. It has no event handlers, no state, no React. Run this, then click Mark read a few times before pressing Run hydrateRoot.

Server HTML, then hydration
import { useState } from "react";
import { renderToString } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { books } from "guide-tools";

function ReadingList() {
  const [read, setRead] = useState<number[]>([]);
  return (
    <section>
      <p>{read.length} read</p>
      <ul>
        {books.slice(0, 3).map((b) => (
          <li key={b.id}>
            {b.title}{" "}
            <button onClick={() => setRead([...read, b.id])} disabled={read.includes(b.id)}>
              Mark read
            </button>
          </li>
        ))}
      </ul>
    </section>
  );
}

// "Server": render the tree to a string.
const html = renderToString(<ReadingList />);
console.log(html);

// Pretend this HTML arrived in the response.
const root = document.getElementById("root")!;
root.innerHTML = html;

// "Client": the JavaScript arrives and React takes over the existing DOM.
document.getElementById("hydrate")!.addEventListener("click", () => {
  const before = root.querySelector("li");
  hydrateRoot(root, <ReadingList />);
  setTimeout(() => console.log("Same <li> node after hydration?", root.querySelector("li") === before), 50);
});
Nothing logged yet.

Before hydration the buttons render, look clickable, and do nothing. That's the gap between "visible" and "interactive" from the last chapter, now in your hands. After hydrateRoot, they work, and the log shows React kept the exact DOM nodes the server sent instead of rebuilding them.

Look at the HTML too: <p>0<!-- --> read</p>. React put an empty comment between the two adjacent text pieces ({read.length} and " read"). The browser would otherwise merge them into one text node, and hydration needs to find each piece separately. Little markers like this are how the server leaves a trail for the client.

Build it: rendering is a tree walk that emits strings#

Server rendering sounds grand, but for plain elements it's a recursive function you've basically written before. In Rendering elements the toy turned elements into DOM nodes. Turn them into strings instead:

A toy renderToString
const escape = (s) =>
  s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");

export function toyRenderToString(node) {
  if (node == null || typeof node === "boolean") return "";
  if (typeof node === "string" || typeof node === "number") return escape(String(node));
  if (Array.isArray(node)) return node.map(toyRenderToString).join("");

  const { type, props } = node;
  // A component: call it and render what it returns. No state, no effects.
  if (typeof type === "function") return toyRenderToString(type(props));

  let attrs = "";
  for (const [key, value] of Object.entries(props)) {
    if (key === "children" || key.startsWith("on") || value == null || value === false) continue;
    const name = key === "className" ? "class" : key;
    attrs += ` ${name}="${escape(String(value))}"`;
  }
  return `<${type}${attrs}>${toyRenderToString(props.children)}</${type}>`;
}
Nothing logged yet.

Three things this toy gets right, and they're the important ones:

  1. Event handlers are dropped. onClick is a function; there's no way to put a function in HTML. Whatever makes the button work has to arrive later, in JavaScript.
  2. Text is escaped. The second book title is an XSS attempt, and both versions output &lt;script&gt;. React escapes everything it renders as text, on the server and the client. (dangerouslySetInnerHTML is the deliberate exception.)
  3. Components are just called. There's no state to keep, no effects to run, no updates. A server render is one pass. useState returns its initial value, useEffect and useLayoutEffect never run, and refs stay empty.

The real one adds the text separators you saw, void elements like <img>, attribute name mapping, the style object, and much more. But the shape is this.

The client half is the mirror image: walk the same element tree alongside the existing DOM and, instead of creating nodes, attach the handlers to the nodes that are already there. You'll build that in the first exercise at the end of the chapter.

renderToString and why it's legacy Legacy#

renderToString(element) is the API from the very first versions of React. It still exists, still works, and is fine for simple cases like rendering an email template. But React's docs steer you to the streaming APIs for real server rendering, because renderToString has three limits:

  • It's synchronous and blocks. The whole tree renders in one go on the server's thread before a single byte goes out.
  • It can't wait for data. If a component suspends, renderToString doesn't wait. It emits that boundary's fallback and marks it for client rendering, so the client has to render that part from scratch after hydration.
  • It can't stream. No early shell, no progressive chunks.

There's also renderToStaticMarkup, which skips the hydration markers. Use it for HTML that will never hydrate, like emails.

Hydration: adopting the server's DOM#

hydrateRoot(container, element, options?) is the client half. It renders element the normal way, building fibers, running components, but in hydration mode: when it would create a DOM node, it instead claims the next existing node in the container and checks that it matches. Event handlers get attached through React's root listeners (React listens at the root and dispatches to fibers), state starts from the initial values, and effects run after commit, exactly as with createRoot.

Three facts follow from that, and interviewers like all three:

  • Hydration renders the whole tree. It's not cheap. Every component runs again in the browser, so hydration time grows with the size of the page, and the component code must be in the bundle.
  • The client's first render must produce the same output as the server's. React assumes it does. If it doesn't, you have a hydration mismatch (covered below).
  • Effects don't run on the server. Anything that needs the browser (reading localStorage, measuring layout, subscribing to events) belongs in an effect or in an event handler, or behind use(browser()) (also below).

hydrateRoot takes the same error options as createRoot (onCaughtError, onUncaughtError, onRecoverableError) plus identifierPrefix, which must match the server's so useId produces the same ids on both sides, and formState, used with Server Functions.

Streaming with renderToReadableStream#

renderToReadableStream(element, options?) returns a promise for a web ReadableStream of HTML. The promise resolves as soon as the shell is ready (everything outside pending Suspense boundaries), and the stream keeps going until every boundary has resolved.

This sandbox does exactly what a browser does with a streamed response, only slowly enough to watch. It reads chunks, logs each one, and writes it into the page. The books take 1.5 seconds to "load" on the server.

Reading the stream chunk by chunk
import { Suspense, use } from "react";
import { renderToReadableStream } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { books, sleep } from "guide-tools";
import { writeChunk } from "./browser.ts";

// A cached promise: the "server" fetch. Starts once, resolves after 1.5 s.
let booksPromise: Promise<typeof books> | null = null;
const getBooks = () => (booksPromise ??= sleep(1500).then(() => books.slice(0, 3)));

function BookList() {
  const list = use(getBooks());
  return <ul>{list.map((b) => <li key={b.id}>{b.title}</li>)}</ul>;
}

function App() {
  return (
    <main>
      <h1>Reading list</h1>
      <Suspense fallback={<p>Loading books...</p>}>
        <BookList />
      </Suspense>
    </main>
  );
}

const start = performance.now();
const stream = await renderToReadableStream(<App />);
console.log(`Shell ready after ${Math.round(performance.now() - start)} ms`);

const reader = stream.getReader();
const decoder = new TextDecoder();
let n = 0;
while (true) {
  const { done, value } = await reader.read();
  if (done) break;
  const html = decoder.decode(value);
  console.log(`Chunk ${++n} at ${Math.round(performance.now() - start)} ms:\n${html}`);
  writeChunk(html);
}

// Give the inline script a moment to reveal the content, then hydrate.
await sleep(400);
hydrateRoot(document.getElementById("root")!, <App />);
console.log("Hydrated");
Nothing logged yet.

Read the two chunks in the console.

Chunk 1, the shell, arrives almost immediately. It has the heading and, where the list goes, the fallback wrapped in markers: <!--$?--> (a pending boundary), an empty <template id="B:0"> that marks the spot, the fallback <p>, and <!--/$--> to close. There's also a one-line script that records when the first frame painted.

Chunk 2 arrives when the data does. It's the rendered list inside <div hidden id="S:0"> (hidden so it doesn't flash at the bottom of the page), plus a script that defines a few tiny functions and calls $RC("B:0", "S:0"). $RC ("reveal completed") finds the template and the hidden div, removes the fallback, and moves the real content into its place. In between, the marker briefly reads <!--$~-->: since React 19.2, completed boundaries are queued and revealed together in a batch, throttled slightly, so several boundaries finishing close together appear at once instead of popping in one after another.

No framework code is involved in that swap. It's a few hundred bytes of inline JavaScript that works before your bundle loads.

One response, streamed in two chunks
Server<App><Header>, <AddBook><Suspense><Books>waiting for dataBrowser document(nothing yet)
Step 1 of 5

A request arrives. The server renders <App>. Inside the Suspense boundary, <Books> suspends: its data isn't ready.

Errors, status codes and the shell#

Streaming changes how errors work, and this is where server rendering gets real:

  • An error in the shell rejects the renderToReadableStream promise. Nothing has been sent, so you can still respond with a 500 and a fallback page.
  • An error inside a Suspense boundary after the shell was sent can't change the status code anymore; the headers are gone. React calls your onError option (log it there), emits that boundary's fallback, and marks the boundary as client rendered (<!--$!-->). On the client, React tries rendering it again from scratch and reports the server error through onRecoverableError.
  • signal lets you abort a slow render. Pending boundaries stay as fallbacks and the client renders them.
  • stream.allReady is a promise that resolves when everything has rendered. Await it before responding when you want complete HTML with no fallbacks, for example for crawlers or static generation.

The options you'll pass most: bootstrapScripts or bootstrapModules (script tags React adds so the client bundle loads and calls hydrateRoot), onError, signal, identifierPrefix and nonce for a Content Security Policy.

Hydrating while the stream is still open#

In a real page you don't wait for the stream to finish. The bundle loads, hydrateRoot runs, and React hydrates whatever has arrived. When it reaches a boundary still marked <!--$?-->, it leaves it alone and registers a retry callback on the marker; the reveal script calls that callback when the content lands.

How does React know the boundary is still coming rather than abandoned? document.readyState. While the server is still streaming, the document is "loading". Once it's complete, a $? boundary will never be filled, so React client-renders it. That's why the sandbox above hydrates only after the stream ends: the sandbox's document finished loading long ago, so an early hydrate would treat the pending boundary as abandoned.

renderToPipeableStream: the Node form#

renderToReadableStream uses web streams, which work in browsers, Deno, Bun, Cloudflare Workers and modern Node. Node also has its own API with callbacks instead of a promise:

server.tsx
import { renderToPipeableStream } from "react-dom/server";
import App from "./App";

app.get("/", (req, res) => {
  let didError = false;
  const { pipe, abort } = renderToPipeableStream(<App url={req.url} />, {
    bootstrapScripts: ["/client.js"],
    onShellReady() {
      // The shell is ready: commit the status code and start streaming.
      res.statusCode = didError ? 500 : 200;
      res.setHeader("Content-Type", "text/html");
      pipe(res);
    },
    onShellError() {
      res.statusCode = 500;
      res.send("<h1>Something went wrong</h1>");
    },
    onAllReady() {
      // Everything rendered. Crawlers and static generation can pipe here instead.
    },
    onError(error) {
      didError = true;
      console.error(error);
    },
  });
  setTimeout(() => abort(), 10_000);
});
client.tsx
import { hydrateRoot } from "react-dom/client";
import App from "./App";

hydrateRoot(document, <App url={location.pathname} />);

onShellReady maps to the renderToReadableStream promise resolving, onAllReady to stream.allReady, and onShellError to the promise rejecting. When the app renders the whole document (<html> down), you hydrate document itself.

Selective hydration#

Hydration in React 17 was one synchronous pass over the whole tree: nothing was interactive until everything was. Since React 18, each Suspense boundary is a unit that can hydrate separately, and React schedules them:

  • The shell hydrates first. Boundaries hydrate as their code and HTML become available.
  • Hydration yields to the browser between units, so a long page doesn't freeze the main thread.
  • If the user interacts with a part that hasn't hydrated yet, React raises that boundary's priority, hydrates it first, and then replays the event.
Selective hydration
Layout (shell)serverNavserver<Suspense> Sidebarserver<Suspense> Commentsserverserver HTML, not interactivehydrating nowhydrated, interactive
Step 1 of 5

The server HTML for the whole page is on screen. Nothing is hydrated yet: the JavaScript is still loading. Dashed boxes are inert server HTML.

This is why Suspense boundaries matter even when no data is involved. With lazy() components inside boundaries, the code for the comments can still be downloading while the rest of the page is already interactive.

Hydration mismatches#

Hydration assumes the client's first render produces exactly what the server produced. When it doesn't, React has to decide which side to trust. Run this one:

Three kinds of mismatch
import { Suspense } from "react";
import { renderToString } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { sleep } from "guide-tools";

function Lucky() {
  return <p>Lucky number: {Math.floor(Math.random() * 1000)}</p>;
}

function Stamp() {
  return <p suppressHydrationWarning>Rendered at {Date.now()}</p>;
}

function Tooltip() {
  return <p title={`id-${Math.random().toFixed(4)}`}>Hover me</p>;
}

function App() {
  return (
    <div>
      {/* Its own boundary, so a mismatch here doesn't throw away the siblings. */}
      <Suspense fallback={null}>
        <Lucky />
      </Suspense>
      <Stamp />
      <Tooltip />
    </div>
  );
}

const root = document.getElementById("root")!;
root.innerHTML = renderToString(<App />);
console.log("Server HTML:", root.innerHTML);
await sleep(30);

hydrateRoot(root, <App />, {
  onRecoverableError(error) {
    console.log("onRecoverableError:", (error as Error).message.split("\n")[0]);
  },
});
await sleep(100);
console.log("After hydration:", root.innerHTML);
Nothing logged yet.

Three different outcomes:

  • Text mismatch (Lucky). React can't patch text cheaply and safely, so it throws away the server HTML for the nearest Suspense boundary (here, the one wrapped around Lucky; without it, the whole root) and client-renders it from scratch. You get a recoverable error that starts "Hydration failed because the server rendered text didn't match the client". The page ends up correct, but you paid for the server render, a discarded hydration and a full client render, and the user may see a flash.
  • suppressHydrationWarning (Stamp). For unavoidable differences like a timestamp, this attribute tells React to accept the server's text for that one element. It works one level deep. Note what it does: the server's value stays on screen. React doesn't patch it.
  • Attribute mismatch (Tooltip). React logs a development warning ("A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up.") and keeps the server's attribute. In production you get no warning and a silently wrong attribute.

The boundary around Lucky matters for this demo: without it, Lucky's mismatch would client-render the whole root, Stamp and Tooltip included, and you'd see neither of the last two behaviors. (One run in a thousand, the random numbers match and Lucky hydrates fine. Run it again.)

The usual causes are in that warning: Date.now() and Math.random() in render, typeof window branches, locale-dependent formatting (the server's time zone isn't the user's), browser-only APIs like matchMedia, data that changed between the server render and hydration, invalid HTML nesting (a <div> inside a <p>, which the browser's parser rearranges) and browser extensions that edit the DOM before React loads.

The fixes, in order of preference:

  1. Make render deterministic. Pass the server's snapshot to the client instead of recomputing (the timestamp as a prop, the data serialized into the page).
  2. Render the browser-only part only in the browser, with use(browser()) (next section), or a two-pass render: render the server-compatible version first and switch in an effect.
  3. suppressHydrationWarning for a single unavoidable text node.

use(browser()): opting out of server rendering React 19.3#

Some components can't produce meaningful HTML on the server: they read localStorage, the user's time zone, the window size. Before 19.3 the options were a typeof window check (which causes mismatches), an isMounted state set in an effect (a second render, and the content still flashes in late), or a framework option to disable SSR for a component.

React 19.3 adds browser() to react-dom. Call use(browser()) in a component and, during server rendering, React stops rendering that component and leaves the closest <Suspense> boundary's fallback in the HTML. In the browser, use(browser()) returns undefined and the component renders normally. Like any use, it can sit behind a condition or an early return.

A browser-only time zone
import { Suspense, use } from "react";
import { browser } from "react-dom";
import { renderToReadableStream } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { sleep } from "guide-tools";
import { writeChunk } from "./browser.ts";

function TimeZone() {
  use(browser("Needs the visitor's time zone."));
  const zone = Intl.DateTimeFormat().resolvedOptions().timeZone;
  return <p>Your time zone: {zone}</p>;
}

function App() {
  return (
    <main>
      <h1>Settings</h1>
      <Suspense fallback={<p>Detecting time zone...</p>}>
        <TimeZone />
      </Suspense>
    </main>
  );
}

const stream = await renderToReadableStream(<App />, {
  onBrowserBailout(error) {
    console.log("onBrowserBailout:", error.message, "| cause:", error.cause);
  },
});
const html = await new Response(stream).text(); // read the whole stream
console.log("Server HTML:", html);
writeChunk(html);

await sleep(1000); // the JavaScript "arrives"
hydrateRoot(document.getElementById("root")!, <App />, {
  onRecoverableError: (e) => console.log("onRecoverableError (not expected):", e),
});
Nothing logged yet.

The server HTML contains the fallback inside a <!--$!--> boundary (client-render this) with the message "Switched to client rendering because a component requested it." For one second the page says "Detecting time zone...", then hydration renders the real component in its place.

The details, from the react.dev reference:

  • The optional reason (a string, or a function that returns one) becomes the cause of the error passed to the server renderer's onBrowserBailout callback. React doesn't put the reason in the HTML.
  • A browser bailout is not reported to onError on the server or to onRecoverableError on the client. It's intended, not a failure.
  • It needs a Suspense boundary above it. Without one the server render fails.
  • It must be called from a client component, not a Server Component, and must be passed to use, never thrown.
  • You can also pass browser() as the reason when aborting a server render (abort(browser("timed out")) or controller.abort(browser())). Pending boundaries then stay as fallbacks and render in the browser, reported through onBrowserBailout.

The react.dev example worth remembering is a data hook that opts out only when it has no initial data: if (options.initialData === undefined) use(browser()). With initial data, the HTML includes the content; without it, the server leaves a fallback and the client fetches.

Strict Mode double-invokes effects during hydration React 19.3#

In development, Strict Mode mounts each component, unmounts it, and mounts it again, so effects run setup, cleanup, setup (Effects explains why). That has been true for createRoot since React 18. Until 19.3, though, roots created with hydrateRoot skipped the double effect run, so code that only broke on remount could pass in a server-rendered app and fail elsewhere. React 19.3 makes hydrated roots match client-rendered ones.

Effects during a Strict Mode hydration
import { StrictMode, useEffect } from "react";
import { renderToString } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";

function Chat() {
  useEffect(() => {
    console.log("connect");
    return () => console.log("disconnect");
  }, []);
  return <p>Chat room</p>;
}

const root = document.getElementById("root")!;
root.innerHTML = renderToString(<Chat />);
hydrateRoot(
  root,
  <StrictMode>
    <Chat />
  </StrictMode>,
);
Nothing logged yet.

You'll see connect, disconnect, connect. If an effect misbehaves here, it was already buggy: it would break the same way when the component remounts for real (with <Activity>, a key change or Fast Refresh).

Prerendering: prerender and partial prerendering#

react-dom/static holds the APIs for generating HTML ahead of time. prerender(element, options?) differs from renderToReadableStream in one way that matters: it waits for all data before resolving, and resolves to { prelude, postponed }, where prelude is a stream of the complete HTML. That's static site generation with full Suspense support.

The interesting case is when you abort a prerender. Whatever finished becomes the prelude, with fallbacks where pending boundaries were, and postponed is a JSON-serializable, opaque description of what's left. Later, at request time, resume(element, postponed) from react-dom/server renders only the missing parts and streams them. This is partial prerendering, the primitive behind Next.js Cache Components. prerender has existed since React 19.0; postponed and resume arrived in 19.2.

Prerender a shell, resume per request
import { Suspense, use } from "react";
import { prerender } from "react-dom/static";
import { resume } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { sleep } from "guide-tools";
import { writeChunk, readAll } from "./browser.ts";

// Request-specific data: we pretend it depends on the visitor's cookie.
let cartPromise: Promise<number> | null = null;
const getCart = () => (cartPromise ??= sleep(300).then(() => 3));

function Cart() {
  const count = use(getCart());
  return <p>Your cart: {count} items</p>;
}

function App() {
  return (
    <main>
      <h1>Store</h1>
      <p>Static product description, the same for everyone.</p>
      <Suspense fallback={<p>Loading cart...</p>}>
        <Cart />
      </Suspense>
    </main>
  );
}

// 1. Build time: prerender, then abort once the static work is done.
const controller = new AbortController();
const pending = prerender(<App />, { signal: controller.signal, onError() {} });
setTimeout(() => controller.abort(), 50);
const { prelude, postponed } = await pending;

const shell = await readAll(prelude);
const stored = JSON.stringify(postponed); // save this next to the HTML (a file, a KV store)
console.log("Static shell:\n" + shell);
console.log(`Postponed state: ${stored.length} bytes of JSON`);

// 2. Request time: send the cached shell instantly, then resume the rest.
writeChunk(shell);
const rest = await resume(<App />, JSON.parse(stored));
const restHtml = await readAll(rest);
console.log("Resumed:\n" + restHtml);
writeChunk(restHtml);

await sleep(400);
hydrateRoot(document.getElementById("root")!, <App />);
console.log("Hydrated");
Nothing logged yet.

The shell is the full page with the cart's fallback in place. The resumed stream is just the missing boundary plus its reveal script, the same shape as chunk 2 in the streaming example. In production the shell would come from a CDN cache and the resume from a server, in one response.

A few things worth knowing about this family:

  • If a prerender isn't aborted, postponed is null: everything was static.
  • resume re-renders from the root until it reaches the parts that weren't finished; fully prerendered subtrees are skipped. Bootstrap scripts are configured on prerender, not resume, and identifierPrefix must match.
  • resumeAndPrerender(element, postponed, options?) React 19.2 in react-dom/static continues an aborted prerender as another prerender: it waits for data and returns a new { prelude, postponed }, so a static build can happen in stages, each of which can itself be aborted and resumed.
  • The Node equivalents are prerenderToNodeStream, resumeToPipeableStream and resumeAndPrerenderToNodeStream.

Resources and metadata from anywhere in the tree React 19.0#

A component deep in the tree often knows what it needs: a stylesheet, a font, its page title. Before React 19 you needed a library like react-helmet or a framework API to get those into <head>. React 19 handles three kinds itself.

Document metadata. Render <title>, <meta> or <link> anywhere and React hoists it into <head>, on the server and the client.

Stylesheets with precedence. <link rel="stylesheet" href="..." precedence="default"> is hoisted, deduplicated, ordered by precedence, and, crucially, React won't reveal a Suspense boundary until the stylesheets inside it have loaded, so content never flashes unstyled.

Resource hints. react-dom exports functions you call during render or in event handlers: preload(href, { as }) to fetch something soon (an image, a font), preinit(href, { as }) to fetch and also execute or insert it (a script or stylesheet), preconnect(origin) to open a connection early, and prefetchDNS(origin) to resolve a domain. There are module variants, preloadModule and preinitModule. On the server these become tags in <head>; in the browser they insert the same tags directly.

Everything lands in head
import { preconnect, prefetchDNS, preinit, preload } from "react-dom";
import { renderToReadableStream } from "react-dom/server";

function BookPage() {
  preload("/covers/refactoring.jpg", { as: "image" });
  preconnect("https://cdn.example.com");
  prefetchDNS("https://stats.example.com");
  preinit("/reviews-widget.js", { as: "script" });
  return (
    <article>
      <title>Refactoring | Reading list</title>
      <meta name="description" content="Martin Fowler, 1999" />
      <link rel="stylesheet" href="/book.css" precedence="default" />
      <h1>Refactoring</h1>
    </article>
  );
}

function Document() {
  return (
    <html>
      <head>
        <meta charSet="utf-8" />
      </head>
      <body>
        <BookPage />
      </body>
    </html>
  );
}

const stream = await renderToReadableStream(<Document />, { bootstrapScripts: ["/main.js"] });
const html = await new Response(stream).text();
console.log(html.replaceAll("><", ">\n<"));
Nothing logged yet.

Everything the component declared ends up in <head>: the preconnect and DNS hints first, then the stylesheet, a low-priority preload for the bootstrap script, the async widget script, the image preload, and the title and description. The <article> in the body contains only the heading. React orders these by how much they matter to the first paint, not by where you wrote them.

Pitfalls#

Check your understanding#

Build itBuild a toy hydrate

toyRenderToString (read-only) produced the HTML in the container. Implement toyHydrate(element, dom) in lib.js: walk the element tree alongside the existing DOM and attach event handlers to the nodes that are already there. Don't create or replace any nodes.

  • For a function component, call it with its props and hydrate what it returns against the same DOM node.
  • For a host element, check that dom is an element with the same tag. If not, throw an error whose message starts with "Hydration mismatch".
  • Attach every prop that starts with on as an event listener (onClick becomes "click").
  • Then hydrate each child element against the matching DOM child element, in order. Ignore text children (the helper childElements gives you only element children).
// Returns only the element children (skips text, numbers, null), flattened.
export function childElements(children) {
  return [children].flat(Infinity).filter((c) => c !== null && typeof c === "object");
}

export function toyHydrate(element, dom) {
  // TODO: function components, tag check, listeners, then children.
}
Nothing logged yet.
Fix itFix the build stamp

This page server-renders a footer with Date.now(), so hydration always fails and React rebuilds the whole page in the browser. Fix it so hydration succeeds with no recoverable error, the stamp still reads "Page built at", and the Likes button still works. There's more than one valid fix.

import { useEffect, useState } from "react";
import { renderToString } from "react-dom/server";
import { hydrateRoot } from "react-dom/client";
import { sleep } from "guide-tools";

function Stamp() {
  return <p className="stamp">Page built at {Date.now()}</p>;
}

function Likes() {
  const [n, setN] = useState(0);
  useEffect(() => {
    (window as any).hydrated = true;
  }, []);
  return <button onClick={() => setN(n + 1)}>Likes: {n}</button>;
}

function Page() {
  return (
    <main>
      <Likes />
      <Stamp />
    </main>
  );
}

const root = document.getElementById("root")!;
root.innerHTML = renderToString(<Page />); // the "server"
await sleep(20); // the JavaScript takes a moment to arrive

(window as any).hydrationErrors = [];
hydrateRoot(root, <Page />, {
  onRecoverableError(error) {
    (window as any).hydrationErrors.push(error);
    console.log("Recoverable:", (error as Error).message.split("\n")[0]);
  },
});
Nothing logged yet.
PredictPredict the markup

What does renderToString(<p>Hello, {name}!</p>) produce when name is "Ada"? And what does it produce for <p>{"Hello, " + name + "!"}</p>?

Quick checkWhat React does on a mismatch

During hydration in React 19, a text node's content differs between the server HTML and the client render, and there's a Suspense boundary around that component. What happens?

Explain it out loudFrom request to interactive

An interviewer asks: "Walk me through what happens, from the request to an interactive page, when a React app uses streaming SSR with a Suspense boundary around slow data."

Interview angle

Say it in 30 seconds

Server rendering walks the component tree once and emits HTML: no state updates, no effects, and event handlers can't travel in HTML. Hydration is the client half: hydrateRoot renders the same tree in the browser, but instead of creating DOM nodes it adopts the server's nodes and attaches handlers, so the first client render must match the server's output. Streaming with renderToReadableStream or renderToPipeableStream sends the shell first and streams each Suspense boundary later as hidden HTML plus a tiny swap script, and selective hydration hydrates those boundaries independently, prioritizing whatever the user touches.

What is hydration, and why is it needed?

basic

What causes hydration mismatches and how does React 19 handle them?

intermediate

What happens on the wire when React streams a Suspense boundary?

senior

What is selective hydration?

intermediate

Why is renderToString considered legacy, and what replaced it?

basic

How do prerender and resume enable partial prerendering?

senior

React 19.3 added use(browser()). What does it do and when would you use it?

senior

Recap#

  • Server rendering is a tree walk that emits HTML: handlers are dropped, text is escaped, effects never run. Hydration is a client render that adopts the existing DOM and attaches handlers.
  • renderToString is legacy: synchronous, no waiting for data, no streaming. renderToReadableStream (web streams) and renderToPipeableStream (Node) send the shell first and stream each Suspense boundary as hidden HTML plus a $RC swap script.
  • Selective hydration treats each Suspense boundary as a separate unit, prioritizes the one the user interacts with, and replays the event.
  • A text mismatch makes React client-render the nearest Suspense boundary (recoverable error); attribute mismatches are warned about and not patched. Fix by making render deterministic, use(browser()) React 19.3, a two-pass render, or suppressHydrationWarning for one unavoidable text node.
  • prerender waits for everything; aborting it yields a shell and a postponed state that resume and resumeAndPrerender continue React 19.2. Strict Mode now double-invokes effects during hydration React 19.3.
  • React 19 hoists <title>, <meta>, <link> and precedence stylesheets into <head>, and preload, preinit, preconnect and prefetchDNS declare resources from anywhere in the tree.

Sources#