React › Static Site Generation (SSG) & Hydration
What is hydration mismatch, and what commonly causes this error in a React app using server rendering?
IntermediateAnswer
A hydration mismatch happens when the actual HTML sent from the server does not exactly match what React expects to render in the browser during hydration, often caused by rendering something differently based on data that only exists in the browser, like the current time or a random value, or a browser only API like window.
// Causes a mismatch, this differs between server and browser
function Greeting() {
return <p>Current time: {new Date().toLocaleTimeString()}</p>;
}
// Fixed, only shows this after hydration completes in the browser
function Greeting() {
const [time, setTime] = useState(null);
useEffect(() => setTime(new Date().toLocaleTimeString()), []);
return <p>Current time: {time || 'Loading'}</p>;
}Real-world example A team fixes a confusing console warning about a hydration mismatch, tracing it back to a component that displayed the current time differently on the server versus the browser, resolved by only showing it after the component mounts in the browser.