React v16 ServerSide Rendering

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.