Server-Side Rendering (SSR) & Hydration
While standard Client-Side Rendering (CSR) works well for internal tools, public web platforms require fast initial load speeds, search engine optimization (SEO), and social media link previews. Server-Side Rendering (SSR) compiles React components into HTML on a web server before sending them to the browser.
In this lesson, you will explore the rendering spectrum (CSR vs SSR vs SSG vs ISR), understand the Hydration lifecycle, and resolve hydration mismatches.
The Rendering Spectrum
CSR (Client-Side Rendering) ──► Browser downloads JS shell; renders DOM in-memory.
SSR (Server-Side Rendering) ──► Server generates HTML on every request; browser hydrates.
SSG (Static Site Generation) ──► HTML built once at compile time; served via CDN.
ISR (Incremental Regeneration) ──► Static pages rebuild in the background on demand.
What is Hydration?
When an SSR page loads in the browser:
- The browser receives complete HTML from the server and paints it immediately (fast First Contentful Paint).
- The user sees the text and layout, but interactive buttons do not respond yet because JavaScript has not executed.
- The browser downloads the client JavaScript bundle.
- React executes on the client and attaches event listeners to the existing HTML markup. This process is called Hydration.
Understanding Hydration Mismatches
A Hydration Mismatch error occurs when the HTML generated by the server does not match the Virtual DOM tree calculated by the client during initial hydration.
Common causes:
- Using browser-only APIs (
window.innerWidth,localStorage) during render. - Rendering dynamic time values (
new Date().toLocaleTimeString()) that differ between server clock and client clock. - Invalid HTML nesting (e.g. placing a
<div>inside a<p>tag, which browsers auto-repair).
Resolving Hydration Mismatches:
import { useState, useEffect } from 'react';
function ClientOnlyTime() {
const [mounted, setMounted] = useState(false);
useEffect(() => {
setMounted(true);
}, []);
if (!mounted) {
return <span className="skeleton">--:--</span>;
}
return <span>{new Date().toLocaleTimeString()}</span>;
}
Best Practices
- Keep Server & Client Markup Identical: Ensure initial render passes output identical JSX on both server and client.
- Use SSG/ISR for Content Pages: Use static pre-rendering for blogs and marketing pages; use SSR for dynamic user dashboards.
- Adopt Modern Meta-Frameworks: Rely on frameworks like Next.js or Remix rather than building custom SSR Express configurations from scratch.
Summary
Server-Side Rendering delivers fast initial page loads and superior SEO by generating HTML on the server. Understanding the hydration process and preventing DOM mismatches ensures smooth, interactive web performance.