React - Server-rendered markup (renderToString)

About

server-rendered markup is one of the output format of Server-side rendering where the React components are:

  • rendered by a node server (at runtime or at build time) by generating HTML pages via a function and are added to the HTTP response to send a HTML page.
  • hydrated on the client side (ie attach event listeners to the server output)

Rendering

The pages will become active, or hydrated, when the JavaScript bundle has loaded.

There is two moments where you can render:

  • at runtime - rendered on the server (the files are created on demand)
  • at build time - rendered at build time (a lot of static files are created)

Runtime

At runtime, means that the node server will render when an HTTP request is made.

Example:

const http = require('http')
const page = require('./.next/serverless/pages/about.js')
const server = new http.Server((req, res) => page.render(req, res))
server.listen(3000, () => console.log('Listening on http://localhost:3000'))

Build time

You can render (ie create the pages) at build time which is called prerendering / snapshoting

You don't need a node server.

See Web - Prerendering / Snapshoting (Dynamic to Static Web Site Generation)

Example

With the Welcome element.

  • The definition of Welcome tag
function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
const myPage = <Welcome name="Nico" />;
const  toHydrateHtml = ReactDOMServer.renderToString(myPage);
  • If you would be on a server, you would use it like that. Example with a Node HTTP server
// http.createServer(function (req, res) {
//       res.writeHead(200, {'Content-Type': 'text/html');
//       res.write(toHydrateHtml);
//       res.end();
//}).listen(port);
  • In our case, we just output it to the console
console.log("React SSR content to hydrate (see client side) with react attribute:");
console.log(toHydrateHtml);
  • Output:

API

Server Side

Server side: You can use this methods to generate HTML on the server and send the markup down on the initial request for faster page loads and to allow search engines to crawl your pages for SEO purposes:

Client Side

On the client side (javascript serverd), you can hydrate the content with ReactDOM.hydrate() on a node that already has this server-rendered markup.

It allows to have a very performant first-load experience.

With a server rendering:

const body = renderToString(<App />);

The index.js client would looks like:

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';

window.onload = () => {
  ReactDOM.hydrate(<App />, document.getElementById('root'));
};

Documentation / Reference


Powered by ComboStrap