Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

I've got code like the following where I'm calling ReactDOM.hydrate. This is shared code that sometimes gets called from the node server and sometimes in the client browser. Do I need to do anything different (then calling hydrate) when calling it on the client only. Normally, I'd call render.

const render = Component => {
 ReactDOM.hydrate(
    <Router history={browserHistory}>
        <FullPage />
    </Router>,
    document.getElementById('root')
 )
}

render(App);

like image 209
Peter Kellner Avatar asked Jan 15 '18 00:01

Peter Kellner


People also ask

Is ReactDOM render necessary?

The render() function is one of the most useful and important functions of ReactDOM. it returns a reference to the component after rendering a React element into the DOM in the provided container (or returns null for stateless components).

What is used instead of ReactDOM render?

Use createRoot instead" occurs because the ReactDOM. render method has been deprecated. To solve the error, create a root element and use the ReactDOMClient.

What is the use of ReactDOM hydrate?

React hydration is a technique used that is similar to rendering, but instead of having an empty DOM to render all of our react components into, we have a DOM that has already been built, with all our components rendered as HTML.

Is ReactDOM render still used?

The render() method of the react-dom package is considered legacy starting react-dom version 18. The method is replaced with the createRoot() method that is exported from react-dom/client . The createRoot() method takes the root element as a parameter and creates a React root.


1 Answers

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(...)
like image 140
Fawaz Avatar answered Nov 15 '22 20:11

Fawaz