ReactJS Client-Side Hydration
ReactJS is known for making creating interactive, stateful UIs easy. React is also known for increasing your time to first load, and for creating interfaces that are not easily understood by search engine crawlers.
Both are very bad things and might not be suitable for a production application 😆
The reason for both of the above issues with React is that React applications generally return ONLY the following HTML to the browser initially:
…and then they kick off the react rendering process which generates all of the rest of your page on the clients browser. Depending on the size and speed of your application, a search engine that opens up your page might only see that single div on your page, and thus miss out on much of the content. Below is an example of the steps involved when a browser runs a classic react application.
One solution to this problem is what is called ‘React Hydration’ or ‘client-side hydration’. In this model you can write your React interface once, run it once on the server, and then again on the client, spreading out the work of rendering your page between the server and the client. This allows you to have the benefits of serverside rendering while still maintaining the interactivity of your site. The image below shows the steps that are followed when the browser opens your app if you are using client side hydration.
- The server receives a request
- The server renders as much of the page as it can
- The server returns a fully rendered HTML page to the browser
- The browser renders the page (now viewable!)
- The browser executes React
- The application is now viewable and interactive
The important methods that you will need to call are both from the ReactDOM client and serverside packages, and they are ReactDOMServer.renderToString(), which you will need to call on the server to generate the rendered page that will be served to the browser, and ReactDOM.hydrate() which will be called on the browser or client side to imbue the static page from the server with all the interactivity of your application.
React hydration is a very popular technique used by many of the leading frameworks including Gatsby as Next.js In most cases these application frameworks hide the details from you, but it always helps to understand the implementation of React Hydration for when you need to build something outside of these frameworks or when you want to optimize your react apps.