← Back to React, page 5

react-0095 · Hard senior

What causes hydration mismatches in server-rendered React, how do you fix them, and what is selective hydration?

Hydration attaches React to server-rendered HTML and expects the first client render to produce the same output. A mismatch happens when the client renders something different from the server HTML, typically because of time, randomness, window checks, locale or browser-only data. React reports a recoverable error and falls back to client rendering of the affected part. Fix it by making the first render deterministic, reading browser-only values after hydration (an effect or useSyncExternalStore with getServerSnapshot), or using suppressHydrationWarning for unavoidable single text differences.

Full answer

Server rendering produces HTML so users see content before JavaScript loads. hydrateRoot(container, <App />) then walks the existing DOM and attaches event handlers and state instead of creating the DOM again. For that to be safe, React expects the first client render to match the server output.

Common causes: Date.now() or new Date() in render, Math.random() or unstable ids, checks such as typeof window !== 'undefined' that change output, reading localStorage or matchMedia during render, locale or time zone differences between server and browser, browser extensions that modify the DOM, and invalid HTML nesting (a div inside a p), which the browser repairs before React sees it.

Result. In development React 19 reports the mismatch with a diff, and in all builds the error goes to onRecoverableError. React cannot trust the server HTML for that part, so it discards it and client-renders the nearest Suspense boundary or the whole root. The page still works, but you lose the benefit of server rendering and may see a flash.

Fixes:

  1. Keep render pure and deterministic. Pass time, locale and ids from the server as props or use useId for ids.
  2. For browser-only values, render a neutral value first and update after hydration: useEffect with state, or better useSyncExternalStore(subscribe, getSnapshot, getServerSnapshot). During hydration React uses getServerSnapshot, so the output matches, and then it re-renders with the client value.
  3. Use suppressHydrationWarning on one element when a text difference is expected, such as a timestamp. It works one level deep and is an escape hatch.
  4. Render client-only widgets in a boundary that does not render on the server (a mounted flag, or lazy with a client-only wrapper).
  5. Validate HTML nesting.

Selective hydration is the related React 18 feature. With Suspense boundaries and streaming, React hydrates boundaries independently and in priority order. If a user clicks inside a boundary that is not hydrated yet, React records the event, raises that boundary's priority, hydrates it, and replays the event. Slow components no longer block interactivity of the rest. Combined with lazy, code for a boundary may load later.

The example simulates a server and a client with different environments, hydrates a naive component and a safe one, and counts the recoverable errors.

jsx
import { useSyncExternalStore } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';

// Stands in for "where this code is running", which differs between server and browser.
let environment = 'server';

function Naive() {
  return <p>Rendered on the {environment}</p>;
}

const subscribe = () => () => {};

function Safe() {
  const where = useSyncExternalStore(subscribe, () => environment, () => 'server');
  return <p>Rendered on the {where}</p>;
}

async function hydrateWith(label, Component) {
  const container = document.createElement('div');
  document.body.appendChild(container);

  environment = 'server';
  container.innerHTML = renderToString(<Component />);
  const serverText = container.textContent;

  environment = 'client';
  const problems = [];
  hydrateRoot(container, <Component />, {
    onRecoverableError: (error) => problems.push(error.message.split('\n')[0]),
  });
  await new Promise((resolve) => setTimeout(resolve, 30));

  console.log(label + ': server text "' + serverText + '", text after hydration "' + container.textContent + '", recoverable errors: ' + problems.length);
  if (problems.length) console.log(label + ' error: ' + problems[0]);
}

await hydrateWith('naive', Naive);
await hydrateWith('safe', Safe);

This ran as a script in the development build of React 19. The "environment" variable simulates the server and the browser producing different values. Output of the run: naive: server text "Rendered on the server", text after hydration "Rendered on the client", recoverable errors: 1 naive error: Hydration failed because the server rendered text didn't match the client. As a result this tree will be regenerated on the client. This can happen if a SSR-ed Client Component used: safe: server text "Rendered on the server", text after hydration "Rendered on the client", recoverable errors: 0

Key points

  • The first client render must match the server HTML. Time, randomness and window checks break it.
  • React reports a recoverable error and client-renders the affected boundary or root.
  • Use deterministic props, useId, useSyncExternalStore with getServerSnapshot, or effects for browser-only values.
  • suppressHydrationWarning is a one-level escape hatch for expected text differences.
  • Selective hydration hydrates Suspense boundaries independently and prioritizes the one the user interacts with.

Common mistakes

  • Reading Date, Math.random or window directly during render in server-rendered components.
  • Hiding the warning everywhere with suppressHydrationWarning.
  • Invalid HTML nesting such as a div inside a p.
  • Reading localStorage during the first render.
  • Ignoring recoverable errors in production monitoring.

Follow-ups

  • How does useId avoid mismatches for generated ids?
  • What happens to a Suspense boundary that mismatches during hydration?
  • How would you render a client-only widget such as a map?

Tips

  • Name three concrete causes. It shows you have debugged it.
  • Explain getServerSnapshot. It is the modern fix.
  • Describe selective hydration with the replayed click.