Hydration
A server rendered application uses the server to generate the HTML for the current navigation. Once the server has completed generating the HTML contents, which also contains the necessary CSS and JSON data to display the static UI correctly, it sends the data down to the client. Since the server generated the markup for us, the client can quickly parse this and display it on the screen, which produces a fast First Contentful Paint!
Although server rendering provides a faster First Contentful Paint, it doesn't always provide a faster Time To Interactive. The necessary JavaScript in order to be able to interact with our website hasn't been loaded yet. Buttons may look interactive, but they aren't interactive (yet). The handlers will only get attached once the JavaScript bundle has been loaded and processed. This process is called hydration
, React checks the current DOM nodes, and hydrates the nodes with the corresponding JavaScript.
The time that the user sees non-interactive UI on the screen is also refered to as the uncanny valley
: although users may think that they can interact with the website, there are no handlers attached to the components yet. This can be a frustrating experience for the user, as the UI may look like it's frozen!
It can take a while before the DOM components that were received from the server are fully hydrated. Before the components can be hydrated, the JavaScript file needs to be loaded, processed, and executed.
If you want the Uncanny Valley
visualized, it looks like this:
Conclusion
As we saw earlier, Hydration refers to the process of attaching event handlers and other interactive functionality to a server-rendered HTML content. It is a crucial step in making a React application interactive on the client-side after the initial server-side rendering (SSR) has taken place. However, if we don't pay attention, we may encounter errors related to hydration, such as the following:
Error: Hydration failed because the initial UI does not match what was rendered on the server.
So, How can we determine the cause of these errors? And how to fix them?