Hydration
Learn how React rehydrates server-rendered HTML to make it interactive on the client.
1. What is Hydration?
Hydration is the process by which React attaches event listeners to server-rendered HTML and transforms it into a fully interactive React application on the client.
When using Server-Side Rendering (SSR) or Static Site Generation (SSG), React renders HTML on the server and sends it to the client. Hydration ensures that this HTML becomes interactive by attaching React's event handlers.
2. How Hydration Works
React uses the ReactDOM.hydrate()
method instead of ReactDOM.render()
to attach event listeners to the existing DOM.
import ReactDOM from 'react-dom'; ReactDOM.hydrate(, document.getElementById('root'));
Explanation: The hydrate
method assumes that the HTML structure rendered on the server matches the React component tree.
3. Benefits of Hydration
- Fast Initial Load: The browser quickly displays server-rendered HTML while React hydrates it in the background.
- SEO Optimization: Search engines can crawl the server-rendered content.
- Reduced Server Load: Only one-time rendering happens on the server, with the client handling further interactions.
4. Key Considerations
- Matching Markup: Ensure that the server-rendered HTML matches the React tree to avoid inconsistencies.
- Use Unique Keys: Properly use keys for dynamic lists to ensure reconciliation works correctly during hydration.
5. Example: Hydration with SSR
// Server-side (Node.js) import ReactDOMServer from 'react-dom/server'; import express from 'express'; import App from './App'; const app = express(); app.get('*', (req, res) => { const html = ReactDOMServer.renderToString(); res.send(` React Hydration ${html}`); }); app.listen(3000, () => { console.log('Server is running on http://localhost:3000'); }); // Client-side (browser) import ReactDOM from 'react-dom'; import App from './App'; ReactDOM.hydrate(, document.getElementById('root'));
Explanation: The server renders the initial HTML, and the client hydrates it to make it interactive.