Q27: What causes React Hydration Mismatch errors during SSR and how do you fix them?

A Hydration error occurs when the pre-rendered HTML string generated on the server doesn't match the initial Virtual DOM tree generated during client-side hydration. Caused by using window checks, Date.now(), or Math.random() directly during render execution.

Fixing Hydration Differences
function DateDisplay() {
  const [formattedDate, setFormattedDate] = useState('');

  useEffect(() => {
    // Safely update on client after hydration completes
    setFormattedDate(new Date().toLocaleDateString());
  }, []);

  return <span>{formattedDate}</span>;
}
💡 Deferring browser-specific date calculations to useEffect prevents SSR HTML mismatch failures.
Key Takeaways
  • Server HTML and initial Client Virtual DOM tree must be identical.
  • Fix by deferring browser-only values to useEffect or disabling SSR using dynamic imports.
Knowledge Check

Why does rendering typeof window !== 'undefined' ? 'Mobile' : 'Desktop' directly in JSX trigger a Hydration error?