There’s been a lot of content around Gatsby 5, and we can’t help but be excited. Today I want to deep dive into a beta feature that is new in Gatsby 5, Partial Hydration.
This happens because the underlying `hydrateRoot()` function can only hydrate the container rendered by ReactDOMServer – which is in Gatsby’s case the entire page – there was no way to do a partial hydration with this method! What this means for users is that all components need to be parsed and initialized before the page can be interactive. This is where Partial Hydration, powered by React Server Components, comes in.
Let’s take a look at using Partial Hydration.
Getting Started with Partial Hydration Today
If you want to get started with Partial Hydration today, we recommend starting with reading our guide in the docs, then checking out the partial-hydration-starter to get a chance to play with code. Let’s take a look at what makes Partial Hydration work in Gatsby by looking at the starter’s components. For an example of a client-rendered component, look at src/components/demo.js:
You can see the comment at the top and the “use client” directive below that– the directive is what establishes a component as a client component. You can find a full list of what makes a component marked for client hydration in the docs. These components have client-side interactions that are not supported in React server components..
When designing your application, it’s important to keep hydration in mind. You’ll need to determine which of your components warrant client-side hydration. A good rule of thumb is, if it needs event listeners, or needs to fetch real-time data, it will need Partial Hydration. There is more information in the documentation on how to architect your app to take advantage of Partial Hydration.
The Future of Partial Hydration
Partial Hydration is still in beta because React Server Components, the concept Partial Hydration is based on, is still in the experimental build of React. Because the APIs might change further before release, we are keeping Partial Hydration in beta until the React Server Components land in the production release of React.
There are a few limitations, as noted in our docs – you can’t use Slices with Partial Hydration currently. You also have to use an experimental version of React, which we do not recommend you use in production.
The docs will also be continuously updated with the status of Partial Hydration in Gatsby, if you ever want to know the latest about Gatsby 5 and Partial Hydration.
Where Can I Learn More?
I hope you enjoyed this deep dive on partial hydration. If you’re interested in learning more about Gatsby 5 in general, there’s an excellent post on Slices, which are cutting build times nearly every time we look, and more info about the Gatsby 5 launch.