FrontendPro

118Implement SSR hydration mismatch detection and a reproduction/fix exercise

hardAbout 60 minutesCodingreactssrhydrationdebugging

Problem

After server rendering, React hydrates: it attaches to the existing HTML, expecting the first client render to produce exactly the same markup. When it does not, React throws the server HTML away for that part of the tree and re-renders it on the client: slower, and a flash of different content.

This profile card has hydration bugs:

function Profile({ name }) {
  const inputId = `note-${Math.random().toString(36).slice(2)}`; // different on server and client
  return (
    <section>
      <h2>{name}</h2>
      <p>Opened at {new Date().toLocaleTimeString()}</p> {/* the clock moved since the server rendered */}
      <label htmlFor={inputId}>Note</label>
      <input id={inputId} />
    </section>
  );
}

Implement (the editor provides react-dom/server and react-dom/client):

  1. hydrateWithReport(container, element): hydrate element into container (which holds server HTML) with hydrateRoot, and resolve, once hydration has settled, with an array of the messages of every recoverable error React reported (hydration mismatches are reported through onRecoverableError).
  2. useHydrated(): false during server rendering and during the hydration render, true afterwards. Use useSyncExternalStore with a server snapshot, not useEffect + state.
  3. A fixed Profile that hydrates without errors: use useId() for the id, and show the time only after hydration (Opened at … with — before that).

Try it yourself

Write your solution, run it, then submit to check it against the tests.

App.jsxReact + DOM

Step-by-step

Render the component to a string (renderToString), put that HTML into a container, and hydrate the same element. Anything that differs between the two renders is a mismatch: random values, Date.now(), typeof window branches, locale or timezone differences, and invalid HTML nesting that the browser repairs.

Unlock the full solution

What's inside

  • Step-by-step
  • Approach
  • Solution
  • Complexity
  • Edge cases
  • Follow-up questions
  • Tests

Includes 2 code listings, 4 edge cases, 4 follow-up questions.

One-time payment by UPI, card or net banking. Launch price.

All 150 answersOne payment, yours forever