Hydration Mismatch Problems
Hydration mismatches occur when the HTML produced on the server does not match what React expects when the browser hydrates the application.
Common causes include rendering Date.now(), random values, browser-only APIs, locale-dependent formatting, or different data between server and client.
A component that depends on browser-only information should usually read that information after hydration or remain entirely client-driven where appropriate.
Avoid Browser-Dependent Initial Render
'use client';
import { useEffect, useState } from 'react';
export default function ClientWidth() {
const [width, setWidth] = useState<number | null>(null);
useEffect(() => {
setWidth(window.innerWidth);
}, []);
return <p>{width === null ? 'Loading...' : `${width}px`}</p>;
}💡 The browser-specific value is read after hydration instead of producing different initial server and client HTML.
Key Takeaways
- Server and client initial output should be consistent.
- Browser APIs do not exist during server rendering.
- Avoid non-deterministic values in server-rendered markup.