← Back to React, page 3

react-0048 · Hard senior

What is hydration, what causes hydration mismatches, and how do you fix them?

Hydration attaches React to HTML that was already rendered on the server, reusing the existing DOM and adding event handlers. For it to work, the client's first render must produce the same output as the server's. A mismatch happens when something differs between the two, such as dates, random values, browser-only checks or invalid HTML nesting. Fix it by making the first render deterministic and moving client-only values into an effect.

Full answer

With server rendering, the server turns components into HTML so users see content before JavaScript loads. The page is not interactive yet. Hydration, started with hydrateRoot(container, <App />), walks the existing DOM next to the component tree, adopts the nodes and attaches handlers. It does not rebuild the DOM, which is why it is fast.

This works only if the first client render matches the server HTML. If a text node or an attribute differs, React cannot trust the markup. In React 19 it reports a recoverable error with a readable diff, through the onRecoverableError option, and falls back to client rendering for the affected part. The page works, but the user may see a flicker and you lose the benefit of server rendering.

The usual causes are:

  • Values that change between renders: Date.now(), new Date() formatted in a different time zone, Math.random(), or any counter written during render.
  • Branches on the environment: typeof window !== 'undefined' inside render shows one thing on the server and another in the browser.
  • Reading localStorage, cookies or media queries during the first render.
  • Invalid HTML nesting, such as a div inside a p, which the browser parser repairs differently from React's output.
  • Browser extensions or CDNs that modify the HTML before React hydrates.

Fixes: render a neutral value first and set the real value in a useEffect, which runs only on the client after hydration. Use useId for identifiers, because it gives the same id on both sides. Use useSyncExternalStore with a getServerSnapshot for browser data. For a single known difference, suppressHydrationWarning on that one element is acceptable, but use it sparingly. Frameworks also offer client-only wrappers.

The example renders on the server renderer, loads the HTML into the container and hydrates it.

jsx
import { Suspense, useEffect, useId, useState } from 'react';
import { hydrateRoot } from 'react-dom/client';
import { renderToString } from 'react-dom/server';

let ticket = 0;

function BadTicket() {
  ticket += 1; // impure: differs between the server and the client render
  return <p>Ticket {ticket}</p>;
}

function GoodYear() {
  const [year, setYear] = useState(null);
  useEffect(() => {
    setYear(2026); // client-only value, set after hydration
  }, []);
  return <p>Year: {year ?? '...'}</p>;
}

function LabelledField() {
  const id = useId(); // same id on server and client
  return (
    <div>
      <label htmlFor={id}>Name</label>
      <input id={id} />
    </div>
  );
}

function App() {
  return (
    <main>
      <Suspense fallback={<p>Loading ticket...</p>}>
        <BadTicket />
      </Suspense>
      <GoodYear />
      <LabelledField />
    </main>
  );
}

const container = document.getElementById('root');
container.innerHTML = renderToString(<App />);
console.log('server html: ' + container.innerHTML);

hydrateRoot(container, <App />, {
  onRecoverableError(error) {
    console.log('recoverable error: ' + error.message.split('\n')[0]);
  },
});

setTimeout(() => console.log('after hydration: ' + container.innerHTML), 80);

BadTicket renders Ticket 1 on the server and a different number on the client, so React reports a recoverable error and re-renders that part on the client. It sits inside a Suspense boundary, so only that part is regenerated, while GoodYear and LabelledField hydrate normally. This was run in jsdom with a React 19 development build. Output of the run: server html: <main><!--$--><p>Ticket <!-- -->1</p><!--/$--><p>Year: <!-- -->...</p><div><label for="_R_3_">Name</label><input id="_R_3_"></div></main> recoverable 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: after hydration: <main><p>Ticket 4</p><p>Year: <!-- -->2026</p><div><label for="_R_3_">Name</label><input id="_R_3_"></div></main>

Key points

  • Hydration reuses server HTML and attaches handlers. The first client render must match it.
  • Mismatches come from time, randomness, window checks, client-only storage and invalid nesting.
  • React 19 reports them through onRecoverableError and recovers by client rendering the part.
  • Fix with deterministic first renders, effects for client-only values, useId and getServerSnapshot.
  • suppressHydrationWarning is a last resort for single, harmless differences.

Common mistakes

  • Using Date.now(), Math.random() or new Date() in render of a server-rendered component.
  • Branching on typeof window inside render.
  • Reading localStorage during the first render.
  • Placing block elements inside paragraph elements.
  • Suppressing every warning instead of finding the difference.

Follow-ups

  • How does useSyncExternalStore with getServerSnapshot avoid mismatches?
  • What is selective hydration and how does Suspense enable it?
  • How would you render a time stamp in the user's time zone without a mismatch?

Tips

  • State the invariant: the first client render must equal the server HTML.
  • List the four common causes from memory. It signals real debugging experience.
  • Give the standard fix, a neutral first render plus an effect.