React question detail
What is React hydration?
React hydration is used to add client-side JavaScript interactivity to pre-rendered static HTML generated by the server. It is used only for server-side rendering(SSR) to enhance the initial rendering time and make it SEO friendly application. This hydration acts as a bridge to reduce the gap between server side and client-side rendering.
After the page loaded with generated static HTML, React will add application state and interactivity by attaching all event handlers for the respective elements. Let's demonstrate this with an example.
Consider that React DOM API(using renderToString) generated HTML for <App> component which contains <button> element to increment the counter.
import {useState} from 'react';
import { renderToString } from 'react-dom/server';
export default function App() {
const [count, setCount] = React.useState(0);
return (
<h1>Counter</h1>
<button onClick={() => setCount(prevCount => prevCount + 1)}>
{count} times
</button>
);
}
const html = renderToString(<App />);
The above code generates the below HTML with a header text and button component without any interactivity.
<h1>Counter</h1>
<button>
<!-- -->0<!-- -->
times
</button>
At this stage hydrateRoot API can be used to perform hydration by attaching onClick event handler.
import { hydrateRoot } from "react-dom/client";
import App from "./App.js";
hydrateRoot(document.getElementById("root"), <App />);
After this step, you are able to run React application on server-side and hydrating the javascript bundle on client-side for smooth user experience and SEO purposes.