%% generate tags start %% #software-engineering %% generate tags end %% #software-engineering/react Hydration in frontend development is a technique in which client-side JavaScript converts a static HTML web page, delivered either through static hosting or server-side rendering, into a dynamic web page by attaching event handlers to the DOM elements. It allows the web page to respond to user interactions, such as clicks and input, and is used in frameworks such as React, Next.js, and Nuxt.js to provide a fast and interactive user experience. in the step until [[HTML#Building Your First SPA]], you will know that you cannot pass any js function to frontend. Therefore interactivity is limited. What if you want to add a onClick function on a button? That is what hydration come in. In React, “hydration” is how React “attaches” to existing HTML that was already rendered by React in a server environment. During hydration, React will attempt to attach event listeners to the existing markup and take over rendering the app on the client. Call `hydrateRoot` to “attach” React to existing HTML that was already rendered by React in a server environment. ```jsx import { hydrateRoot } from 'react-dom/client'; const domNode = document.getElementById('root'); const root = hydrateRoot(domNode, <App />); ``` React will attach to the HTML that exists inside the `domNode`, and take over managing the DOM inside it. An app fully built with React will usually only have one `hydrateRoot` call with its root component. > [!info] see more > [hydrateRoot – React](https://react.dev/reference/react-dom/client/hydrateRoot#reference) ## How is it Done? When a React app _hydrates_, it assumes that the DOM structure will match. When the React app runs on the client for the first time, it builds up a mental picture of what the DOM should look like, by mounting all of your components. Then it squints at the DOM nodes already on the page, and tries to fit the two together. It's not playing the “spot-the-differences” game it does during a typical update, it's just trying to snap the two together, so that _future_ updates will be handled correctly. ## Hydration Error Hydration errors result from **a mismatch between server- and client-rendered markup and differences in component states**. > [!info] read more ✨ > [The Perils of Hydration: Understanding how Gatsby/Next manage server-side rendering and hydration (joshwcomeau.com)](https://www.joshwcomeau.com/react/the-perils-of-rehydration/#hydration--render-7)