A Quick Overview on React DOM Render and Hydrate.
With React 16, lots of new features added, but today we’re taking about what actually the difference between React DOM render and Hydrate (Excited!!!).
Great, so both Render and Hydrate are the modules for the react-DOM package.
As per the official definition “Render is used to render the React Element into the DOM in the supplied container and return a reference to the container (or return null for stateless component)”. For more, please check the below link:
Hydrate is same as render, but it is used to hydrate a container whose HTML contents were rendered by ReactDOMServer API.
Confuse with the above statement, don’t worry, just chill, relax and continue with this blog :)
So hydrate() is used when we want to render our React Application on server side and hydrate the JavaScript bundle on the client side which make our application fast and also allow the search engines to crawl your pages for SEO purposes. Let’s deep dive into the code for better understanding.
Here I am using create react app boilerplate.
This is the simple illustration which display Hello, Ankur in the browser.
But what will happen when we change render method to hydrate, any idea !! Yes, react will throw some warning in you console states “Expected server HTML to contain a matching <h1> in <div>.”
The error clearly shows that if your application does not use server side rendering (SSR), please use reactdom render to start.
So, let’s change the above code to make it as SSR.
SERVER SIDE RENDERING
Create the react component and will mount it in the DOM.
For rendering, i’ll use hydrate of react DOM instead of render for SSR.
First create the server file which basically render the HTML and that server rendered html will hydrate at the client side.
Here name variable is used to pass it to the Hello react component from server file and same name will be use to render it to the client side.
And now the warning gets resolve, WOOOOW!
Thank you for reading! Please share it with anyone who might find it useful.