Quiz

Explain what React hydration is

Topics
React
在GitHub上编辑

TL;DR

React hydration is the process of attaching event listeners and making a server-rendered HTML page interactive on the client side. When a React application is server-side rendered, the HTML is sent to the client, and React takes over to make it dynamic by attaching event handlers and initializing state. This process is called hydration.


What is React hydration?

Server-side rendering (SSR)

Server-side rendering (SSR) is a technique where the HTML of a web page is generated on the server and sent to the client. This allows for faster initial page loads and better SEO since the content is already available when the page is loaded.

Hydration process

Hydration is the process that happens after the server-side rendered HTML is sent to the client. React takes the static HTML and "hydrates" it by attaching event listeners and initializing the state, making the page interactive. This process involves:

  1. Reusing the existing HTML: React uses the HTML generated by the server and does not re-render it from scratch.
  2. Attaching event listeners: React attaches the necessary event listeners to the existing HTML elements.
  3. Initializing state: React initializes the component state and props to make the page dynamic.

Example

Here's a simple example to illustrate the concept:

  1. Server-side rendering: The server generates the following HTML:

    <div id="root">
    <button>Click me</button>
    </div>
  2. Client-side hydration: When the HTML is sent to the client, React hydrates it with the following code:

    import React from 'react';
    import ReactDOM from 'react-dom';
    function App() {
    const handleClick = () => {
    alert('Button clicked!');
    };
    return (
    <button onClick={handleClick}>Click me</button>
    );
    }
    ReactDOM.hydrate(<App />, document.getElementById('root'));

In this example, the server sends the static HTML with a button to the client. React then hydrates the button by attaching the onClick event listener, making it interactive.

Benefits of hydration

  1. Faster initial load: Since the HTML is already available, the initial page load is faster.
  2. SEO benefits: Search engines can crawl the server-rendered HTML, improving SEO.
  3. Improved user experience: Users can see the content immediately, even before React has fully taken over.

Challenges of hydration

  1. Mismatch issues: If the server-rendered HTML does not match the client-side React components, it can cause errors and warnings.
  2. Performance overhead: Hydration can be resource-intensive, especially for large applications.

Further reading

在GitHub上编辑