What's Actually Happening

React throws hydration errors when server-rendered HTML doesn't match client-rendered output.

The Error You'll See

```javascript Warning: Text content did not match. Server: "Logged in" Client: "Not logged in"

Error: Hydration failed because the initial UI does not match what was rendered on the server. ```

Why This Happens

  1. 1.SSR/CSR mismatch - Different content rendered on server vs client
  2. 2.Browser extensions - Modifying DOM before hydration
  3. 3.Date/time rendering - Different timestamps
  4. 4.Random values - Different random numbers
  5. 5.Conditional rendering - Using window/localStorage in SSR

Step 1: Identify Mismatch Source

```javascript // Common causes:

// 1. Using window in SSR: function Component() { const width = window.innerWidth; // Error in SSR! }

// 2. Date rendering: function Component() { return <p>{new Date().toLocaleString()}</p>; // Mismatch! }

// 3. Random values: function Component() { return <div id={Math.random()} />; // Mismatch! } ```

Step 2: Fix SSR/CSR Mismatch

```javascript // Use useEffect for client-only code: function Component() { const [width, setWidth] = useState(0);

useEffect(() => { setWidth(window.innerWidth); }, []);

return <p>Width: {width}</p>; }

// Use suppressHydrationWarning for known mismatches: function Component() { return ( <p suppressHydrationWarning> {new Date().toLocaleString()} </p> ); } ```

Step 3: Fix Conditional Rendering

```javascript // BAD: Conditional based on window function Component() { if (typeof window !== 'undefined') { return <ClientOnly />; } return <Default />; }

// GOOD: Use useEffect function Component() { const [mounted, setMounted] = useState(false);

useEffect(() => { setMounted(true); }, []);

if (!mounted) return <Default />; return <ClientOnly />; } ```

React Hydration Checklist

CheckIssueFix
Window usageSSR crashuseEffect
Date/timeMismatchsuppressHydrationWarning
Random valuesMismatchuseEffect
localStorageSSR crashuseEffect

Verify the Fix

bash
# No hydration warnings in console
# Page renders correctly
  • [Fix React State Not Updating](/articles/fix-react-state-not-updating)
  • [Fix React useEffect Infinite Loop](/articles/fix-react-useeffect-infinite-loop)