top of page
Logo der Online Agentur mdwp

Hydration

Hydration in the context of React JS refers to the process of attaching event listeners to the markup content that is generated by the server during server-side rendering (SSR). The idea is that the server sends HTML to the client (browser) and then React "hydrates" this static version with the ability to respond to user interactions. This process helps in improving the initial page load performance.

Here's a basic example of how this may happen.

Code Snippet:

```jsx
import React from 'react';
import { hydrate, render } from 'react-dom';
import App from './App';

//This checks if the HTML is pre-rendered/rendered by Server Side Rendering (SSR)
if (rootElement.hasChildNodes()) {
hydrate(<App />, rootElement); //If true, hydrate the pre-existing HTML
} else {
render(<App />, rootElement); //If false, simply render the App on the client side
}

//Here, the <App /> is our main React component and rootElement is the HTML node that we want our React app to attach itself to (Typically, it is a div with id 'root' or 'app').
```
In this piece of code, the hydrate method tells React that the HTML content is already rendered on the server side, and it just needs to attach event listeners for fast initial load, instead of generating the HTML all over again.

bottom of page