118Implement SSR hydration mismatch detection and a reproduction/fix exercise
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):
hydrateWithReport(container, element): hydrateelementintocontainer(which holds server HTML) withhydrateRoot, and resolve, once hydration has settled, with an array of the messages of every recoverable error React reported (hydration mismatches are reported throughonRecoverableError).useHydrated():falseduring server rendering and during the hydration render,trueafterwards. UseuseSyncExternalStorewith a server snapshot, notuseEffect+ state.- A fixed
Profilethat hydrates without errors: useuseId()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.
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.