问题
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?
回答1:
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 callReactDOM.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.
回答2:
In addition to above...
ReactDOM.hydrate()
is same as render()
, but it is used to hydrate(attach event listeners) a container whose HTML contents were rendered by ReactDOMServer. React will attempt to attach event listeners to the existing markup.
Using ReactDOM.render() to hydrate a server-rendered container is deprecated because of slowness and will be removed in React 17 so use hydrate()
instead.
回答3:
Hydrate is basically used in case of SSR(Server side Rendering). SSR gives you the skeleton or HTML markup which is being shipped from a server so that for the first time when your page loads it is not blank and search engine bots can index it for SEO(A use case of SSR). So hydrate adds the JS to your page or a node to which SSR is applied. So that your page responds to the events performed by the user.
Render is used for rendering the component on client side browser Plus if you try to replace the hydrate with render you will get a warning that render is deprecated and can't be used in case of SSR. it was removed because of it being slow as compared to hydrate.
回答4:
The entire process of putting functionality back into the HTML that was already rendered in server side React is called hydration.
So the process of re-rendering over the once rendered HTML is referred to as hydration.
So if we try to hydrate our application by calling ReactDOM.render()
its supposed to be done by calling ReactDOM.hydrate()
.
来源:https://stackoverflow.com/questions/46516395/whats-the-difference-between-hydrate-and-render-in-react-16