Skip to content
Search

Hydration

lastmod 2023-08-09created 2023-08-091 edits

In web development, hydration or rehydration 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 HTML elements.

Intro

React v18 is set to add a new Suspense SSR Architecture, and by combining it with React's Suspense, selective Hydratation can now be applied to websites. Hydratation is an essential solution provided by many frameworks and libraries that already offer server-side rendering (Gatsby, Next.js, etc.). I want to take some time to reconsider why people want to use this technique and to summarize how it works.

About

When rendering a web page, Client Side Redering (CSR) libraries such as React fetch the bundled js and render the DOM. Along with many advantages, this approach also has problems such as slow initial rendering and SEO limitations. So Server Side Rendering (SSR) is often chosen depending on the situation, because SSR solves the CSR problems mentioned above. There has been a long debate over whether SSR or CSR is better, but each has had its pros and cons depending on the project and what it prioritizes.

So developers came up with the idea of first rendering a static page on the Server Side, bundling the JS files as well, and then sending both to the Client Side. But that DOM would be in a dried-out state with no dynamic events at all. So a technique emerged that adds moisture to this dried-out skeleton, that is, matches the HTML code with the JS code to render a dynamic website in the browser, and this is Hydratation. So a literal Korean translation of Hydration would be "replenishing moisture".

Next.js successfully delivered this solution using the hydrate feature React has provided since v16. hydrate is a ReactDOM function; let's briefly compare it with the render function you usually write at the start of building a React project.

ReactDOM.render(element, container, [callback]);

The ReactDOM.render() function handles rendering by injecting a given component as a child of the specified DOM element passed as the second parameter. A callback function to handle a particular event once rendering is complete can be passed as the third parameter.

ReactDOM.hydrate(element, container, [callback]);

The ReactDOM.hydrate() function only performs hydrate on a given component as a child of the specified DOM element passed as the second parameter. This means that instead of creating a DOM to build a new web page through rendering, it finds the corresponding DOM elements in the existing DOM Tree and attaches only the designated JavaScript properties (event listeners, etc.).

See also

Favorite site

author Zer0 sitemap