Understanding React Hydration
What is hydration?
With client-side rendering, most actions trigger local DOM updates instead of network requests. Clicking a navigation link builds the requested page on the client instead of requesting it from the server. Because they make fewer network requests, applications rendered in the browser provide a blazing-fast user experience — after the initial download.
Hydration lets you take a hybrid approach.
Note: You’ll sometimes see developers use re-hydration instead of hydration. They’re interchangeable.
Gatsby’s build process uses Node.js and
How Gatsby uses React hydration
Build and render static assets
gatsby build starts up a Node.js server that processes your site: It creates a GraphQL schema, fetches data that your pages will pull in by extracting queries from your code and executing them, and it then renders each page’s HTML. You can read the GraphQL Concepts guide to learn how all parts interact with each other. The “Overview of the Gatsby Build Process” conceptual guide helps explain what’s happening at each step in the build process.
All of this data is gathered during the build and written into the
/public folder. You can customize Gatsby’s configurations for Babel and webpack, as well as the HTML generated by your build, in order to tweak how your site gets built.
hydrateRoot() method is called internally by Gatsby from
react-dom/client, which according to the React docs is:
Same as createRoot(), but is used to hydrate a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.
Please note: If you need to, the hydrateRoot method can be replaced with a custom function by using the
replaceHydrationFunction Browser API.
This means that the browser can “pick up” where the server left off with the contents created by Gatsby in the
/public folder and render the site in the browser like any other React app would. Since the data and structure of the pages is already written out, it’s not necessary for Gatsby to go to another server asking for HTML or other data.
If you don’t need the aforementioned app-like features everywhere and only need a bit of interactivity on your page here and there, then you should use Gatsby’s Partial Hydration feature. It enables you to only mark specific parts of your site as interactive while the rest of your site stays static by default. There will be no React hydration for these static portions. Follow the Partial Hydration how-to guide to learn more.
- Rendering on the Web from Google
- ReactDOMClient.hydrateRoot() from the React API Reference
- Partial Hydration Conceptual Guide