Course contentsShow
← React
Lesson 1657 of 2,39640. Server-Side RenderingFree lesson

Common Cause: Conditional Rendering Based on State

Recognizing mismatches from useState initialized differently on server versus client first render.

Common Cause: Conditional Rendering Based on State

What you'll learn: How useState initialized on the server can cause hydration mismatches when it renders differently on the client's first pass.

The Problem

When you use useState in a component that gets server-rendered, React initializes that state with its default value on the server. Then, when the client hydrates, React initializes the same state again with the same default value. So far, so good—but here's the trap:

If your component conditionally renders based on that state, and something causes the initial state to be different between server and client (like a timestamp or random value), you get a mismatch.

The Sneaky Case

Even without random values, you can cause mismatches if you're not careful:

function ThemeToggle() {
  // Server always initializes to false
  const [isDark, setIsDark] = useState(false);
  
  // ❌ Mismatch if you read localStorage on mount!
  useEffect(() => {
    const saved = localStorage.getItem('theme');
    if (saved === 'dark') setIsDark(true);
  }, []);
  
  return <div className={isDark ? 'dark' : 'light'}>Content</div>;
}

What happens: Server renders className="light". Client's first render also uses false (the initial state), so it renders className="light". Hydration succeeds! But then the useEffect runs, updates state to true, and React re-renders with className="dark". This creates a "flash of wrong theme."

The mismatch isn't during hydration—it's the pattern of initializing state one way on the server but immediately changing it on the client based on browser-only data.

The Fix

Accept that the first render will always match the server. Use useEffect to update after hydration completes, and design your UI to handle that initial state gracefully (perhaps with a brief flash or neutral default).

Key Takeaway: Initialize useState with values that will be identical on both server and client first renders—save browser-specific state changes for after hydration in useEffect.