In React, OK to always call ReactDOM.hydrate instead of ReactDOM.render? In React, OK to always call ReactDOM.hydrate instead of ReactDOM.render? reactjs reactjs

In React, OK to always call ReactDOM.hydrate instead of ReactDOM.render?


hydrate do works similar to render on client side whether the HTML has server rendered markup or not, but when there is no markup previously like not SSR then hydrate produces some warnings but, it will render your markup as expected.A better way to solve this would be to check if its SSR (assuming root as your parent div id) :

var isMarkupPresent = document.getElementById('root').hasChildNodes();

and then you can either render or hydrate:

isMarkupPresent ? hydrate(...) ? render(...)


Strictly speaking, no it is not safe to always use ReactDOM.hydrate().

From the docs on hydrate, you should only use it on "a container whose HTML contents were rendered by ReactDOMServer". hydrate also expects that the server rendered markup is identical to what the client side render outputs, and any differences should be considered bugs.

ReactDOM.render() on the other hand is used to render your app into an empty container on the client. You may need to do this if you don't have server rendered markup on all pages.

Because render() handles a use case that hydrate() does not, it is not safe to say "you can always use ReactDOM.hydrate()".