Skip to content
FrontDepth, Home

React & Rendering

Server rendering and hydration

How React apps reach the browser as HTML and become interactive: CSR, SSR, static and streaming rendering, what hydration does, why mismatches happen and how to fix them, selective hydration and the cost of the interactivity gap.

MiddleSeniorUpdated 16 November 2026

Reading level

Shows sections up to the selected level.

This topic starts at Middle level.

MiddleConcept

CSR, SSR, static and streaming rendering

The same React app can reach the browser in several ways. They differ in where and when the first HTML is produced, and that decides what the user sees first and when the page responds.

  • Client-side rendering (CSR). The server sends an almost empty <div id="root"></div> and a bundle. The browser downloads and runs the JavaScript, fetches the data and only then builds the DOM with createRoot. Hosting is cheap, but and wait for the bundle and the data, and as the app grows, so does the JavaScript that competes with input (INP).
  • Server-side rendering (SSR). For every request the server renders the components to HTML. The browser paints the content before any script runs; then makes it interactive. Rendering takes server time on each request, which can raise TTFB.
  • Static rendering (SSG). The HTML is rendered at build time, one file per URL, and served from a CDN. TTFB is consistently fast and there is no per-request server work, but the page is only as fresh as the last build, and anything per-user still has to be rendered in the browser.
  • Streaming SSR. The server sends HTML in chunks: first the shell of the page with <Suspense> fallbacks, then each slow part when its data is ready. The first bytes no longer wait for the slowest query.
First HTMLTTFBFCP / LCPInteractiveCost
CSRempty shellfastlate: after JS and datawhen the bundle has runstatic hosting
SSRfull page per requestslower: server renders firstearlyafter hydrationserver work per request
SSGfull page from the buildfast, from a CDNearlyafter hydrationrebuilds; stale between them
Streaming SSRshell first, rest in chunksfastearly for the shellboundary by boundaryserver work per request

Two things are easy to miss. First, SSR and SSG do not remove JavaScript: to hydrate, the browser still downloads and runs the same components. web.dev's "Rendering on the Web" warns that you are often building the same app twice, once on the server and once on the client. Second, these are per-route choices, not per-app ones: a marketing page can be static, a product page streamed, and an editor client-rendered.

renderToString still works, but it returns a string at once: it neither streams nor waits for data. For new code react.dev points to renderToPipeableStream (Node.js streams) and renderToReadableStream (Web Streams: Deno, edge runtimes), and to prerender / prerenderToNodeStream for static generation.

MiddleFramework

What hydration does

Hydration makes server HTML interactive without rebuilding it. hydrateRoot(domNode, reactNode) renders your component tree in the browser as usual, but instead of creating DOM nodes it walks the nodes that are already in the document, claims them one by one in the same order and attaches the event handlers. When it finishes, the root behaves like any client-rendered root.

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

app.get("/products", (req, res) => {
  const { pipe } = renderToPipeableStream(<App />, {
    bootstrapScripts: ["/client.js"],
    onShellReady() {
      res.setHeader("Content-Type", "text/html");
      pipe(res);
    },
  });
});
JSX
import { hydrateRoot } from "react-dom/client";
import { App } from "./App";

hydrateRoot(document, <App />);

Here App renders the whole <html> document, so the client hydrates document. The server sends HTML plus a <script> that loads client.js; the browser paints the HTML immediately and runs the script when it arrives.

It must produce the same tree

Hydration is not a "diff and patch" step. React assumes the first client render produces exactly the output the server produced, and react.dev asks you to treat every mismatch as a bug. Checking every attribute of every node would make hydration too slow for the common case where nothing differs, so React does not do it.

That means the first client render may only use what the server also had:

  • the same components and the same props;
  • the same data, which frameworks serialize into the page (a JSON script or the Server Components payload) so the client does not fetch it again;
  • no browser-only inputs: localStorage, window.matchMedia, the device's time zone, a random number.

What it costs

Hydration skips creating DOM nodes, not rendering. Every component on the page still has to be downloaded, parsed and run once on the . Until that work is done, the page looks ready but React's event handlers are not attached yet. This gap, and how to shrink it, is covered in the senior sections below.

MiddlePitfalls

Why hydration mismatches happen

A mismatch means the first client render produced something different from the server HTML. React 19's own error message lists the usual suspects, and every one of them is a value that differs between the two environments:

  • A server/client branch, such as if (typeof window !== "undefined").
  • Variable input: Date.now(), new Date(), Math.random().
  • Locale and time zone formatting. The server usually runs in UTC with one locale; the user's browser has its own.
  • External data without a snapshot sent along with the HTML: the client fetched newer data, or read a browser store.
  • Invalid HTML nesting. The browser's HTML parser repairs the markup, so the DOM is not what React rendered.
  • Browser extensions that change the HTML before React loads.

The classic: reading localStorage during render

JSX
function useTemperatureUnit() {
  const [unit, setUnit] = useState(() =>
    typeof window === "undefined" ? "C" : (localStorage.getItem("unit") ?? "C"),
  );
  return [unit, setUnit];
}

The guard keeps the server from crashing, but it also guarantees two different first renders for everyone who saved a preference: the server renders 21 °C, the browser of a user who chose Fahrenheit renders 70 °F. A test account with default settings never sees the bug; it appears only for users with saved settings, once the page hydrates.

Time zones and locales

JavaScript
const placedAt = Date.UTC(2026, 10, 16, 22, 30);

new Date(placedAt).toLocaleDateString("en-US", { timeZone: "UTC" });
new Date(placedAt).toLocaleDateString("az-AZ", { timeZone: "Asia/Baku" });

The first call gives "11/16/2026", the second "17.11.2026": in Baku it is already the next day. Late-evening orders are only wrong for users in some time zones, which is why this bug survives testing.

Invalid nesting

<p>Total: <div>{price}</div></p> is invalid HTML. The parser closes the <p> before the <div>, so the DOM built from the server HTML is <p>Total: </p><div>…</div><p></p>, and React finds nodes it did not render. In development React warns: "In HTML, <div> cannot be a descendant of <p>. This will cause a hydration error."

Counters as ids

A module-level nextId++ gives different ids on a long-running server than in a fresh browser. useId exists for this: it derives the id from the component's position in the tree, which is the same on both sides as long as the trees match.

The Incident Simulator's Hydration mismatch: the page rebuilds itself incident lets you practise debugging a hydration mismatch from production telemetry.

MiddleFramework

What React 19 does on a mismatch

React treats differences in text or elements and differences in attributes differently. The table shows what React 19.3 does in each case (checked in Chromium with the development and production builds):

DifferenceDevelopmentProductionDOM after hydration
Text or element, no <Suspense> around iterror with a server/client diffMinified React error #418the whole root is re-created
The same, inside a <Suspense> boundarythe same error#418only that boundary is re-created
An attribute (className, href, id)console warningnothingthe server's value stays
Text inside an element with suppressHydrationWarningnothingnothingthe server's text stays

Text and element mismatches

React cannot hydrate a subtree whose content differs, so it throws away the server HTML up to the nearest <Suspense> boundary (or the whole root when there is none) and renders that part again on the client. The development message says so: "Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client."

The page keeps working, but the recovery is expensive and visible:

  • every regenerated node is new, so text typed into an input before hydration finished is gone and focus is lost;
  • the render work is done twice, on a page that was already busy loading;
  • content can jump while the new nodes replace the old ones.

Attribute mismatches

React does not regenerate anything for an attribute. In development it logs "A tree hydrated but some attributes of the server rendered HTML didn't match the client properties. This won't be patched up." In production it says nothing, and the DOM keeps the server's value. A wrong href or aria-* attribute can therefore live in production unnoticed.

Reporting

These errors are recoverable: React reports them and keeps going. Send them to your error tracker; in production, #418 is the only visible sign of the bug.

JSX
hydrateRoot(document, <App />, {
  onRecoverableError(error, errorInfo) {
    reportToTracker(error, errorInfo.componentStack);
  },
});

Browser extensions

React 19 skips unexpected tags in <head> and <body> that third-party scripts or extensions inserted, instead of treating them as a mismatch. If it has to re-render the whole document for an unrelated mismatch, it leaves stylesheets inserted by extensions in place. Extensions that change text inside your components can still cause mismatches, so check a suspicious report in a clean browser profile before you hunt for a bug in your code.

SeniorExample

Fixing mismatches the right way

The rule behind every fix: the first client render may use only what the server also knew. Browser-only values come after hydration, or the server has to learn them.

1. Render the server's value, then update in an Effect

For the hook above:

JSX
function useTemperatureUnit() {
  const [unit, setUnit] = useState("C");

  useEffect(() => {
    const saved = localStorage.getItem("unit");
    if (saved) setUnit(saved);
  }, []);

  return [unit, setUnit];
}

The first render matches the server HTML, React keeps the existing DOM, and the Effect applies the saved unit right after hydration. react.dev calls this two-pass rendering; its cost is one more render and a visible switch from °C to °F.

2. useSyncExternalStore with getServerSnapshot

For a value that lives in a browser store and can change later, pass a third argument. React uses getServerSnapshot on the server and during hydration, then re-renders with getSnapshot if the value differs:

JSX
const subscribe = (onChange) => {
  window.addEventListener("storage", onChange);
  return () => window.removeEventListener("storage", onChange);
};

function useSavedUnit() {
  return useSyncExternalStore(
    subscribe,
    () => localStorage.getItem("unit") ?? "C",
    () => "C",
  );
}

getServerSnapshot must return exactly the same value on the server and on the first client render. The storage event fires only in other tabs, so code that writes the value in this tab must notify the subscribers itself.

3. Let the server know

Both fixes still show °C until the JavaScript has run. The real fix is to keep the preference where the server can read it: a cookie or the user's profile. The server renders the right unit, the client gets the same value as a prop, and nothing changes after hydration. The same goes for time zones and locales: format with an explicit timeZone and locale that both sides receive, instead of each environment's default.

4. suppressHydrationWarning, only for unavoidable text

JSX
<time dateTime={iso} suppressHydrationWarning>
  {new Date(iso).toLocaleTimeString()}
</time>

It silences the warning for that one element's text and attributes (one level deep). It does not fix anything: React does not patch the text, so the server's value stays on screen until the next render. For a saved preference it would only hide the error: users would keep seeing the server's value.

5. Client-only components

React 19.3 adds browser() to react-dom. Calling use(browser()) in a Client Component inside a <Suspense> boundary makes the server leave the fallback in the HTML; the browser then renders the component. This is not a recoverable error; the server can log it through onBrowserBailout. The older pattern, still shown on react.dev's Suspense page, throws an error on the server inside a boundary.

SeniorFramework

Streaming and selective hydration

Before React 18, server rendering was all-or-nothing in three ways: the server had to fetch everything before it could send anything, the client had to load all the code before it could hydrate anything, and it had to hydrate everything before the user could interact with anything. Streaming and selective hydration remove those three waits, and both are built on <Suspense>.

Streaming the HTML

JSX
function ProductPage() {
  return (
    <Layout>
      <ProductGrid />
      <Suspense fallback={<ReviewsSkeleton />}>
        <Reviews />
      </Suspense>
    </Layout>
  );
}

Everything outside <Suspense> boundaries is the shell. renderToPipeableStream calls onShellReady as soon as the shell is rendered, and you start piping. The HTML contains ReviewsSkeleton in place of the reviews. When Reviews has its data, React writes its HTML into the same response together with a small inline <script> that swaps out the fallback, before React itself has loaded in the browser. Design the shell to be "minimal but complete": a skeleton of the real layout, not a page-wide spinner.

Trade-offs to know:

  • Once you have started streaming, you can no longer change the status code. Errors inside the shell are reported to onShellError (send a fallback page); errors inside a boundary are reported to onError, the boundary's fallback is sent, and the client retries rendering that part.
  • Crawlers and static generation can wait for onAllReady and receive the complete HTML.
  • abort() after a timeout makes React send the remaining fallbacks and render those parts on the client.

Selective hydration

Hydration happens per <Suspense> boundary. React can hydrate the shell and the boundaries whose code and HTML have arrived without waiting for a slow chunk or a lazy component elsewhere. If the user clicks inside a boundary that is not hydrated yet, React raises its priority and hydrates it first (the React 18 architecture write-up says it does so synchronously during the click's capture phase).

Boundaries also limit the damage of a mismatch: React re-creates only the boundary in which the difference was found, so state and DOM outside it survive. A page whose only boundary is the root loses everything on a single wrong value.

Boundaries are not free, though: each one is a point where a fallback can appear. Put them around parts that are slow (data or code) or independent (comments, recommendations, a chat widget), not around every component.

SeniorWeb platform

The interactivity gap and the cost of hydration

Server HTML is painted before React runs, so for a while the page looks ready but React has not attached its event handlers yet. web.dev describes it this way: server-rendered pages can appear loaded and interactive but cannot respond to input until the client scripts have run. The gap is often called the uncanny valley. On a fast laptop it lasts milliseconds; on a mid-range phone with a large bundle it can last seconds.

What the user experiences

  • Buttons whose behaviour is a React onClick do nothing. Real links and forms still work, because the browser handles them natively.
  • Inputs accept typing, because they are plain HTML elements. If hydration later regenerates that tree after a mismatch, the typed text is lost.
  • Clicks that land during a long hydration task wait until it finishes. That delay counts towards INP, and long tasks during load show up in TBT, while LCP looks great. A dashboard that only watches LCP will not see the problem.

Why it costs so much

Hydration is work proportional to the size of the client tree: download, parse and run every component, then attach the listeners. The data is often paid for twice, once as HTML and once as serialized JSON for the client render.

Shrinking the gap

  • Ship less code to hydrate. With Server Components (for example the Next.js App Router), only modules marked 'use client' and what they import are bundled for the browser. Server Components send their rendered output, not their code, and are not hydrated. Client Components are still rendered to HTML on the server and hydrated. Push 'use client' down to the interactive leaves (a search box, a like button), not to whole layouts.
  • Split with <Suspense> so the important parts hydrate first and the rest does not block them.
  • Lazy-load below-the-fold widgets and third-party scripts.
  • Keep render cheap: no heavy computation in components that run during hydration.
  • Degrade gracefully: real <a href> and <form action> elements still do something before hydration.

Measure it rather than guess: record a page load with CPU throttling in the Performance panel, look for the long hydration task after the HTML is painted, and track INP from real users.

SeniorInterview tips

Interview tips

A 30-second answer. "SSR renders HTML on the server so content appears before JavaScript runs. Hydration then runs the same components in the browser, claims the existing DOM and attaches event handlers. It assumes the first client render matches the server HTML exactly. If text differs, React re-creates that part of the tree up to the nearest Suspense boundary; if attributes differ, it keeps the server's values."

Questions you are likely to get

  • CSR vs SSR vs SSG vs streaming: which would you choose? Compare them on TTFB, FCP/LCP, INP, freshness and cost, then choose per route: static marketing pages, streamed product pages, a client-rendered editor.
  • What causes hydration mismatches? typeof window branches, dates and time zones, Math.random(), reading localStorage or matchMedia during render, invalid nesting, extensions. Explain why each one makes the two renders differ.
  • How do you fix one? Render the server's value first and update in an Effect; use useSyncExternalStore with getServerSnapshot; better still, make the value known to the server (a cookie). Use suppressHydrationWarning only for unavoidable text such as a timestamp.
  • What do streaming and selective hydration solve? The three waits: fetch everything, load everything, hydrate everything. Mention the shell, the inline scripts that swap fallbacks, and hydration in priority order.
  • Why is the page visible but unresponsive? The interactivity gap: HTML is painted, handlers are not attached yet. Tie it to INP and to bundle size.

Mistakes that cost points

  • Saying hydration "renders the page again into the DOM". It renders the components again but reuses the server's nodes.
  • Calling suppressHydrationWarning a fix. It hides the warning; the wrong text stays.
  • Saying React patches every difference. Attributes are not patched; text and elements are re-created, not fixed in place.
  • Saying SSR means less JavaScript. Without Server Components the same code still ships to hydrate.

Senior signal

Talk about operations: report onRecoverableError with the component stack per release, test hydration with saved preferences and in other time zones and locales, and treat typeof window, Date and localStorage in render code as review red flags. And know where mismatches show up: in error rates and lost input, rarely in load metrics such as LCP.

MiddleReview checklist

What to check when reviewing SSR and hydration code

Use this list when you review server-rendered components you did not write: a teammate's, a library's or an AI assistant's. expects the first client render to match the server HTML exactly; otherwise React re-creates part of the page, losing typed input and focus, and wrong attributes stay unnoticed in production.

  • Does the first render read browser-only values? typeof window branches, localStorage or window.matchMedia in render or a useState initializer make it differ from the server's, and a test account with default settings never shows it. Render the server's value and update in an Effect, use useSyncExternalStore with getServerSnapshot, or keep the value in a cookie the server reads.
  • Are dates and random values the same on both sides? new Date(), Date.now(), Math.random() and toLocaleDateString() without an explicit timeZone and locale give the server and the browser different text. Test the page in another time zone and locale.
  • Is suppressHydrationWarning kept for unavoidable text such as a timestamp? It silences the warning one level deep and fixes nothing: the server's text stays until the next render.
  • Is the HTML nesting valid, and are ids made with useId? In <p>Total: <div>…</div></p> the parser closes the <p> early, so the DOM is not what React rendered; a module-level nextId++ gives different ids on a long-running server and in a fresh browser.
  • Does hydrateRoot get an onRecoverableError that reports to the error tracker? In production a text mismatch shows only as Minified React error #418, and an attribute mismatch shows nothing.
  • Are slow or independent parts in their own <Suspense> boundary? A mismatch then re-creates only that boundary, not the whole root, and the rest of the page hydrates without waiting for it.

Check your understanding

  • Practice

    Predict-output and open interview questions with self-assessment.

    3 predict-output · 4 open

  • Quiz

    Multiple-choice questions with explanations and a score.

    5 questions

Hands-on work that uses this topic.