Course contentsShow
← Web Development
Lesson 1748 of 2,98232. Server-Side Rendering ConceptsFree lesson

Conditional Rendering During Hydration

Handling browser-only code and dynamic content that differs between server and client environments.

Conditional Rendering During Hydration

You'll learn how to safely handle code and content that only belongs in the browser, preventing hydration mismatches when server and client environments differ.

The Core Challenge

During server-side rendering, your code runs in Node.js where browser APIs like window, localStorage, or document don't exist. But after hydration, the same components run in the browser where these do exist. If you naively reference browser-only code, you'll either crash the server build or create hydration mismatches when the client renders something different from what the server sent.

The Solution Pattern

Conditional rendering during hydration means deliberately showing nothing or a placeholder on the server, then revealing browser-specific content only after hydration completes. This keeps server and client output identical on first render, preventing mismatches.

Common Example: User Timezone

function UserGreeting() {
  const [timezone, setTimezone] = useState(null);

  useEffect(() => {
    // Only runs in browser after hydration
    setTimezone(Intl.DateTimeFormat().resolvedOptions().timeZone);
  }, []);

  if (timezone === null) {
    return <div>Loading location...</div>; // Server and initial client show this
  }

  return <div>Your timezone: {timezone}</div>; // Only after hydration
}

The server renders "Loading location..." and so does the initial client render—no mismatch! Then useEffect fires (browser-only), updates state, and shows the real timezone.

The Trade-off

You're accepting a brief flash of placeholder content to maintain hydration integrity. It's a small price for avoiding crashes and console errors.

Key Takeaway: When content depends on browser-only APIs or differs between server and client, render a safe placeholder initially and only show the real content after hydration completes via effects.