All topics
Advancedadvanced

Hydration and Hydration Mismatches

Understand how React attaches interactivity to server-rendered HTML, and why mismatches between server and client output cause errors.

Hydration is the process by which React takes server-rendered, already-present HTML and 'attaches' its interactive JavaScript behavior to it, rather than tearing it down and re-rendering from scratch on the client. React walks the existing DOM structure alongside the component tree it would have rendered, matching them up and attaching event listeners and internal fiber state to the already-present nodes, ideally without needing to modify the DOM at all if everything lines up correctly.

Hydration is like an usher matching ticket holders to seats that are supposedly already set up exactly as printed on the tickets — if a seat doesn't match what the ticket says (a mismatch), the usher can't just quietly seat them there; the whole row has to be re-set-up on the spot, defeating the point of having pre-arranged seating at all.

Key Concepts

1
A hydration mismatch occurs when the HTML React expects to find (based on running the same component tree on the client) doesn't match what the server actually sent — commonly caused by using values that differ between server and client environments, like Date.now(), Math.random(), checking typeof window !== 'undefined' to branch rendering, or locale-dependent formatting that resolves differently in different environments.
Date.now()Math.random()typeof window !== 'undefined'
2
When React detects a mismatch, it logs a hydration warning and falls back to discarding the mismatched server-rendered content, re-rendering that portion entirely on the client instead — which both loses the performance benefit SSR was meant to provide for that content and can cause a visible flash as the corrected client-rendered version replaces what briefly appeared from the server. This is exactly the class of problem useId (covered elsewhere) was introduced to solve for one common ID-generation source of mismatches.
useId
3
Interviewers ask candidates to identify likely sources of hydration mismatches in a given snippet — common answers include Math.random()-based keys, rendering the current time, environment-dependent conditional rendering, and browser extensions that modify the DOM before React hydrates it — and to explain what actually happens to the DOM when a mismatch is detected.
Math.random()