Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the difference between hydrate() and render() in React 16?

I've read the documentation, but I didn't really understand the difference between hydrate() and render() in React 16.

I know hydrate() is used to combine SSR and client-side rendering.

Can someone explain what is hydrating and then what is the difference in ReactDOM?

like image 735
shabenda Avatar asked Oct 01 '17 20:10

shabenda


People also ask

Is hydrate faster than render?

render will flush out anything in the specified element(named as 'root' in most cases) and rebuild it ,while hydrate will keep anything that is already inside the specified element and build from that,making the initial page load faster.

What is hydration in rendering?

In web development, hydration or rehydration is a technique in which client-side JavaScript converts a static HTML web page, delivered either through static hosting or server-side rendering, into a dynamic web page by attaching event handlers to the HTML elements.

What does a render () method in ReactJS return?

Purpose of render(): React renders HTML to the web page by using a function called render(). The purpose of the function is to display the specified HTML code inside the specified HTML element. In the render() method, we can read props and state and return our JSX code to the root component of our app.

What is the difference between render and mount in React?

Render is a class-based component that gets called and returns the set of instructions for creating DOM. Mounting is when the component renders first time and indeed builds the initial DOM from that instruction.


1 Answers

From the ReactDOMServer docs (emphasis mine):

If you call ReactDOM.hydrate() on a node that already has this server-rendered markup, React will preserve it and only attach event handlers, allowing you to have a very performant first-load experience.

The text in bold is the main difference. render may change your node if there is a difference between the initial DOM and the current DOM. hydrate will only attach event handlers.

From the Github issue that introduced hydrate as a separate API:

If this is your initial DOM:

<div id="container">     <div class="spinner">Loading...</div> </div> 

and then call:

ReactDOM.render(    <div class="myapp">       <span>App</span>    </div>,    document.getElementById('container') ) 

intending to do a client-side only render (not hydration). Then you end with

<div id="container">    <div class="spinner">        <span>App</span>    </div> </div> 

Because we don't patch up the attributes.

Just FYI the reason they didn't patch the attributes is

... This would be really slow to hydrate in the normal hydration mode and slow down initial render into a non-SSR tree.

like image 127
topher Avatar answered Sep 19 '22 16:09

topher