惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

B
Blog RSS Feed
量子位
Recent Announcements
Recent Announcements
T
The Blog of Author Tim Ferriss
美团技术团队
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
Blog — PlanetScale
Blog — PlanetScale
H
Help Net Security
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
博客园 - Franky
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
宝玉的分享
宝玉的分享
大猫的无限游戏
大猫的无限游戏
V
Visual Studio Blog
博客园 - 聂微东
aimingoo的专栏
aimingoo的专栏
Microsoft Security Blog
Microsoft Security Blog
U
Unit 42
J
Java Code Geeks
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
IT之家
IT之家
Hugging Face - Blog
Hugging Face - Blog
腾讯CDC
L
LangChain Blog

DEV Community

Authentication Security Deep Dive: From Brute Force to Salted Hashing (With Java Examples) Why AI Systems Don’t Fail — They Drift Spilling beans for how i learn for exam😁"Reinforcement Learning Cheat Sheet" I Replaced Chrome with Safari for AI Browser Automation. Here's What Broke (and What Finally Worked) How Python Borrows Other People's Work The $40 Architecture: Processing 1 Billion API Requests with 99.99% Uptime Vibe Coding: A Workflow Guide (From Zero to SaaS) Most webhook security guides protect the wrong side. The scary part is delivery. Headless CMS for TanStack Start: Build a Blog with Cosmic EU Age Verification App "Hacked in 2 Minutes" — What Actually Happened Comfy Cloud’s delete function does not actually remove files Running AI Models on GPU Cloud Servers: A Beginner Guide Event-driven media intelligence with AWS Step Functions and Bedrock I scored 500 AI prompts across 8 quality dimensions — here's what broke How to Call Google Gemini API from Next.js (Free Tier, No Backend Needed) The Portal Protocol: Reclaiming Human Connection in the Age of AI How to Fix Your Team's Scattered Knowledge Problem With a Self-Hosted Forum Intro to tc Cloud Functors: A Graph-First Mental Model for the Modern Cloud Designing Multi-Tenant Backends With Both Ownership and Team Access I Built a Neumorphic CSS Library with 77+ Components — Here's What I Learned PostgreSQL Performance Optimization: Why Connection Pooling Is Critical at Scale Cómo construí un SaaS multi-rubro para gestionar expensas en Argentina con FastAPI + Vue 3 🚀 I Built an Ethical Hacking Scanner Tool – Open Source Project I Replaced /usage and /context in Claude Code With a Single Statusline A Pythonic Way to Handle Emails (IMAP/SMTP) with Auto-Discovery and AI-Ready Design I Collected 8.9 Million Polymarket Price Points — Here's What I Found About How Markets Really Move EcoTrack AI — Carbon Footprint Tracker & Dashboard Everyone's Using AI. No One Agrees How. 5 self-hosted ebook managers worth trying in 2026 Building Your First AI Agent with LangChain: From Chatbot to Autonomous Assistant
Hydration in React/Next.js : Understand in 3 Minutes
Hongster · 2026-04-30 · via DEV Community

Hydration in React/Next.js

The Problem Statement

Hydration is the process where a server-rendered HTML page becomes an interactive React application on the client. You hit this problem when your Next.js page loads instantly (thanks to server-side rendering) but then suddenly flickers, loses state, or feels janky as JavaScript kicks in. Sound familiar? You’ve likely seen the dreaded “hydration mismatch” warning in your console. It happens because the static HTML the server sent doesn’t perfectly match the React tree the browser tries to build. Why does this matter? Because without proper hydration, your app can break functionality like click handlers, form inputs, or third-party widgets that rely on client-side JavaScript.

The Core Explanation

Hydration is the bridge between static HTML and dynamic React. Here’s how it works in three steps:

  1. Server sends dry HTML: Next.js renders your React components on the server, producing plain HTML with no JavaScript. This HTML is fast to display—users see content immediately.

  2. Browser renders that HTML: The browser paints the page. It looks complete, but nothing is interactive yet—no buttons work, no dropdowns open.

  3. React “waters” the HTML: React’s JavaScript bundle downloads and runs. React attaches event listeners (like onClick), initializes component state, and connects the virtual DOM to the existing DOM nodes. This is hydration—React takes the server’s static markup and brings it to life.

The catch? React expects the server-sent HTML structure to exactly match what it would render on the client. If there’s any difference—say, a useEffect that changes something on mount, or a component that uses window.innerWidth—React throws a mismatch error and re-renders the whole tree. That’s where performance issues and user-facing glitches start.

Simple analogy: Think of a pre-filled form on paper. Server sends you a printed form with all fields filled. Hydration is you taking that paper form, scanning it, and turning it into an editable digital document where you can click buttons and type. If the digital version has a different layout (extra field, missing label), the scan fails.

The Practical Context

Use hydration when you need fast initial page loads and SEO, which is almost every server-rendered Next.js app. Hydration is automatic in Next.js for pages using getServerSideProps or getStaticProps. You don’t opt in—you opt out.

Avoid hydration when your page has no dynamic content at all. If every visitor sees exactly the same static marketing page, skip React entirely and use a plain HTML/CSS approach. Also, avoid heavy hydration for pages that rely heavily on client-only data (like dashboards) – consider using next/dynamic with ssr: false to skip server rendering entirely for those components.

Real-world use cases:

  • E-commerce product pages: SEO needs server-rendered content, but “Add to Cart” buttons and image galleries need hydration. Mismatches here cause cart logic to break silently.
  • Blog with comments: Server renders the article; hydration enables live comment submission without a page reload. Mismatch often happens if the server shows a logout button but the client knows the user is logged in.
  • Admin dashboards: You may prefer client-only rendering for authenticated pages to avoid hydration mismatch with user-specific data.

Why should you care? Hydration mismatches cause bugs that are hard to reproduce—they happen only on first load, then disappear on subsequent navigations. They degrade Core Web Vitals (Layout Shifts from re-renders) and user trust.

The Quick Example

Here’s a common hydration mismatch and how to fix it:

// ❌ Problem: uses client-only data during server render
function Greeting() {
  const [name, setName] = useState('')
  useEffect(() => {
    // This runs only on client – server sends empty name
    setName(localStorage.getItem('username'))
  }, [])
  return <h1>Hello, {name}</h1>
}

// ✅ Fix: ensure server output matches client initial render
function Greeting() {
  const [name, setName] = useState('')
  useEffect(() => {
    // Same logic, but initial state is 'User' – both sides match
    setName(localStorage.getItem('username') || 'User')
  }, [])
  return <h1>Hello, {name}</h1>
}

Enter fullscreen mode Exit fullscreen mode

What this demonstrates: The server renders <h1>Hello, </h1> (empty name). The client tries to build the same, but useEffect runs and sets name to a stored value. React detects a difference ('' vs 'Alice') and throws a hydration mismatch. By initializing useState with a fallback value that matches server output, you prevent the mismatch. The useEffect will still update the UI after hydration—but without re-rendering the whole page.

The Key Takeaway

Always make your server-rendered output identical to your component’s initial client render—ensure useState default values and any conditions based on typeof window are consistent. For deeper dives, read React’s official hydration documentation.