Hydration is the step in which JavaScript in the browser attaches event handlers and application state to HTML that a server already rendered. Here it means the web technique, although search results also show the term in the sense of fluid intake. Some developers say re-hydration, and the two terms are interchangeable (Gatsby).
How does hydration work?
The server sends finished HTML, so content is visible before any JavaScript has loaded. The browser then loads the JavaScript, and the framework takes over the existing markup. Examples and API names here come from React; other frameworks use the term with their own APIs. In React this is done with hydrateRoot, which attaches React to HTML that was already rendered by React in a server environment. It replaced the older hydrate function in React 18. An app that is rendered only in the browser and has no server-rendered HTML uses createRoot instead.
React expects the server HTML and the first render in the browser to be identical and treats mismatches as bugs. Common causes are checks like typeof window !== 'undefined', browser-only APIs in rendering logic, and different data on server and client. In the best case a mismatch slows the page down, in the worst case event handlers attach to the wrong elements.
Relevance for SEO
When the server-rendered HTML already contains the content, crawlers see text and links without running JavaScript. Gatsby’s documentation notes that rendered HTML makes it easier for search engines and social media crawlers to consume a site. Google lists hydration, next to server-side and static rendering, as a recommended alternative to dynamic rendering.
Example
import { hydrateRoot } from 'react-dom/client';
hydrateRoot(document.getElementById('root'), <App />);
The root element already contains the server-rendered HTML. React adds the interactivity.
Sources
- hydrateRoot – React Docsreact.dev
- hydrate (deprecated) – React Docsreact.dev
- Understanding React Hydration – Gatsby Docsgatsbyjs.com
- Dynamic rendering as a workaround – Google Search Centraldevelopers.google.com
Last updated: