DeployU
Interviews / Frontend Engineering / This component causes a hydration mismatch error. Why and how to fix it?

Questions

This component causes a hydration mismatch error. Why and how to fix it?

debugging SSR & Hydration Interactive Quiz Code Examples
Wrong Approach

Just add suppressHydrationWarning to hide the error.

Right Approach

That hides the symptom, not the cause. Hydration errors occur when the initial client render doesn't match the server HTML. The fix is to defer client-only logic to useEffect:

Why It Happens:

  • Server has no window → always renders “Desktop User”
  • Client has window → might render “Mobile User” on first render
  • React sees the mismatch and throws a warning

The Rule: First client render must be identical to server render. Use useEffect for client-only APIs.

ResponsiveWelcome - Fix Hydration Mismatch
Your Code
import React, { useState, useEffect } from 'react';

export default function ResponsiveWelcome() {
  // THE BUG: Server vs client render differently
  const isMobile =
    typeof window !== 'undefined' && window.innerWidth < 768;

  const message = isMobile
    ? 'Welcome, Mobile User!'
    : 'Welcome, Desktop User!';

  return <h1>{message}</h1>;
}
const code = document.querySelector('[data-editor]').textContent;
if (!code.includes('useState(false)')) throw new Error('Test failed: Use useState(false) to match server render.');
if (!code.match(/useEffect[\s\S]*?window\.innerWidth/)) throw new Error('Test failed: Move window check inside useEffect.');
if (!code.match(/useEffect[\s\S]*?setIsMobile/)) throw new Error('Test failed: Call setIsMobile in useEffect.');
console.log('✓ All tests passed! Hydration mismatch fixed correctly.');
Click "Run Code" to see output...
Click "Run Code" to see test results...

The Solution

export default function ResponsiveWelcome() {
  // 1. Default state matches server render
  const [isMobile, setIsMobile] = useState(false);

  // 2. Client-only check runs after hydration
  useEffect(() => {
    const checkIsMobile = () => window.innerWidth < 768;
    setIsMobile(checkIsMobile());

    // Optional: handle resize
    const handleResize = () => setIsMobile(checkIsMobile());
    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  const message = isMobile ? 'Welcome, Mobile User!' : 'Welcome, Desktop User!';
  return <h1>{message}</h1>;
}

The initial render uses isMobile: false, matching the server. Then useEffect runs and updates if needed.

Practice Question

What is the most common cause of a React hydration mismatch error?