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

The useEffect Solution Pattern

Deferring browser-dependent logic to useEffect to ensure server and client initial renders match.

What You'll Learn

You'll learn how to fix hydration mismatches by deferring browser-dependent logic to useEffect, ensuring the server and client initial renders produce identical HTML.

The Problem Recap

When you use browser APIs like window.innerWidth or new Date() directly in your component's render logic, the server renders one thing (often a fallback or error), but the client renders something different on first pass — causing a hydration mismatch.

The useEffect Solution

The fix is simple: render the same safe default on both server and client initially, then update to the real value only on the client using useEffect.

Here's the pattern:

function WindowWidth() {
  const [width, setWidth] = useState(null); // Safe default

  useEffect(() => {
    // This only runs on the client, after hydration
    setWidth(window.innerWidth);
  }, []);

  if (width === null) {
    return <div>Loading width...</div>; // Both server and client render this first
  }

  return <div>Width: {width}px</div>;
}

Why This Works

  • Server renders: Sees width === null, outputs "Loading width..."
  • Client first render (hydration): Also sees width === null, outputs "Loading width..." — perfect match!
  • After hydration: useEffect runs, updates state to real width, triggers re-render with actual value

The initial renders match because useEffect doesn't run on the server or during the client's first render — it only runs after hydration completes.

The Trade-Off

You'll see the fallback value briefly (sometimes just a flash). That's the price of hydration safety. For non-critical UI like tooltips or analytics, this is acceptable.

Key Takeaway: Move browser-dependent code into useEffect to ensure server and client render the same HTML initially, then safely update on the client after hydration.