React v16 ServerSide Rendering

Toru Kobayashi
Oct 1, 2017 · 2 min read

If you do SSR for your React Application using React v15, you need to use renderToString to generate a markup to use it on browser. In addition to that, If you’d like to generate entirely HTML of a page with React, you need to use renderToStaticMarkup and combine them like the following.

This is an example of SSR using React v15.

React v15

  • App.js
  • Html.js
  • server.js
  • browser.js

To do that, you need to generate HTML, added a checksum and some attributes, from App Component and embed it in Html Component by dangerouslySetInnerHTML.

In server.js, you need to generate HTMLs with renderToString and renderToStaticMarkup.

As the result, the HTML generated by renderToString and the ReactElement generated by ReactDOM.render match, which means the DOM generated by SSR is reused on ReactDOM.render.

React v16

In React v16, React doesn’t use any checksum to validate markups and has an explicit API called ReactDOM.hydrate to reuse SSR markups on browser, which means you don’t need to match the entry point between server and browser. (If you still need to use ReactDOM.render and want to reuse SSR markups, you have to match the entry point because ReactDOM.render needs data-reactroot attribute for hydration)

As the result, you can write the above example using React v16 like the following, which is using renderToNodeStream which is added in v16.

App.js

  • Html.js
  • server.js
  • browser.js

Great! You don’t need to generate the markup from your App Component to reuse it on browser anymore! You just use renderToNodeStream and just pass the component as the children of the DOM element that is the target of ReactDOM.hydrate.

As a result, Your SSR code becomes very simple and efficient with React v16.

Welcome to a place where words matter. On Medium, smart voices and original ideas take center stage - with no ads in sight. Watch
Follow all the topics you care about, and we’ll deliver the best stories for you to your homepage and inbox. Explore
Get unlimited access to the best stories on Medium — and support writers while you’re at it. Just $5/month. Upgrade

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store