Skip to main content

Command Palette

Search for a command to run...

Hydration

Updated
3 min read
Hydration
A

Hey devs, I'm MERN Stack Developer from India. let's infer our knowledge together.

meaning - process of combining two things

Hydration

The process of adding interactivity to already existing HTML.

or
The process of attaching event listeners and internal states to an already existing server-rendered DOM.

Does Hydration happens in CSR ?

This is a modern frontend concept. If you only work with CSR, you might not have heard about it.

So first, let's understand what happens in a typical CSR framework/library.

<body>
  <div id="root"> </div> or <app-root></app-root> 
  <script src="main.js"></script>
</body>

When main.js loads, there is no pre-rendered HTML available to attach JavaScript.

React or Angular build the DOM from scratch using methods like:

  • createRoot (React)

  • bootstrap (Angular)

So in CSR, hydration does not apply(Generally). So lets move to next step, the modern frontend concepts introduced in the frontend world i.e. SSR, SSG etc.

Now Let's see when the Hydration comes.

SSR

SSR (Server Side Rendering) was introduced to improve:

  • Initial page load

  • SEO

In SSR, the server sends already rendered HTML to the browser.

However, JavaScript for the entire app is still sent to the browser, so hydration becomes necessary.

Now you should have a clear idea of what hydration means.

Next, let's talk about the problem introduced by hydration and the solutions.

Hydration Flow :

Server → render HTML
        ↓
Browser → shows page (looks ready)
        ↓
**Uncanny Valley**
   UI looks interactive
   but JS is not loaded yet
   clicks do nothing
        ↓
Browser → download JS
        ↓
React → hydrate DOM
        ↓
Page → interactive

The Problem: Hydration Waterfall

React hydrates the DOM starting from the root element.

Root
 ↓
Children
 ↓
Grandchildren

lets say we have the below component structure.

Here:

  • Header, Article, Footer → static

  • Comments → interactive

<App>
 ├── Header
 ├── Article
 ├── Comments
 └── Footer

Hydration order:


Hydrate Header
      ↓
Hydrate Article
      ↓
Hydrate Comments
      ↓
Hydrate Footer

Even If only Comment component is interactive, React still waits for Header and Article component to hydrate first

Header hydration finished
      ↓
Article hydration finished
      ↓
Comments hydration begins

This is known as Hydration waterfall problem.

Solution

Reduce hydration
 ├─ Selective Hydration → React
 ├─ Streaming SSR → React / Next.js
 ├─ Suspense → React
 ├─ React Server Components → React / Next.js
 └─ Code Splitting → React / Next.js / Angular

Mostly avoid hydration
 ├─ Islands Architecture → Astro / Fresh / Marko
 └─ Partial Hydration → Astro / Marko

Remove hydration completely
 └─ Resumability → Qwik

note - in React/Next.js Hydration still occurs, it just reduces the cost of hydration. Only Astra and Qwik solves this problem