React - Server-rendered markup (renderToString / hydrate)

About

server-rendered markup is the dynamic possibility of server-side rendering (vs static).

The steps are:

Advantages

  • Faster page loads: The html is rendered. The page does not need to load the javascript bundle to render.
  • SEO purposes: It allow search engines to crawl your pages without Javascript.

The disadvantage is that the architecture is more complicated and you need to take into account where your code will be running (ie on the server or on the browser).

Steps

Server: Html page creation

On the server side, you can use of this two methods to generate HTML with react data attributes:

  • ReactDOMServer.renderToString(..) 1) to render a React element to its initial HTML. React will return an HTML string.
  • ReactDOMServer.renderToNodeStream(element) 2) - Returns a Readable stream



The below example shows you how to create a page on the server side with the ReactDOMServer.renderToString(..) 3) function.

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}
const App = <Welcome name="Foo" />;
  • The rendering to transform the component in reacted HTML
const  toHydrateHtml = ReactDOMServer.renderToString(App);
  • The creation of the HTML page where /static/bundle.js is the classic React bundle (see client_bundle) that will start the hydratation (tree building) after loading.
const htmlPage = `
<!doctype html>
<html>
  <head>
	<title>Dynamic SSR example</title>
  </head>
  <body>
  
        <div id="root">
        
        <!-- The reacted HTML inside the root div element -->
        ${toHydrateHtml}
        
        </div>

        <!-- The classic bundle (client) that calls the building of the tree with the hydratation when loaded -->     
        <script  src="/static/bundle.js">
  </body>
</html>
`;
  • 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(htmlPage);
//       res.end();
//}).listen(port);
  • In our case, we just output it to the console.
console.log(htmlPage.trim());
  • Output: The page send will look like that:

Client: Hydratation React bundle

This section shows you how to create the bundle.js file added to the pages created on the server side.

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

The bundle is a classic javascript bundle but:

The client.js (start point for the bundle.js file) client would looks like (import/export statement excluded)

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

Code Demo

A fully functional demo repository can be found here if you want to take a look.

Library / Tool

Next

A full server framework with own link/image/routing component React Framework - Next.js. Doc

Razzle

A framework that tries to do no more than basic server side rendering and lets you choose all other library (routing/…).

razzle (https://razzlejs.org/docs/how-it-works)

2 configs, 2 ports, 2 webpack instances, both watching and hot reloading the same filesystem, in parallel during development and a little webpack.output.publicPath magic.

Deprecated

Open source is hard…

Rendering Time

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.

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)

Documentation / Reference





Discover More
How to render React on the Server (SSR) in Static Markup (renderToStaticMarkup)?

This page shows you how to render React in a static HTML page (known in React as static markup) - ie only HTML element without any React properties or React library. The page then doesn't need to be hydrated....
React - App Architecture

An architecture could be: taking static site snapshots of all your publicly-accessible pages leaving anything requiring authentication as a normal, JS-driven Single Page App.
React - Deployment - Routing for client side router

With client side router, a direct HTTP call will failed if you are not using some routing features (such as ) For a create-react-app React application, all URL must be redirected to the index.html...
React - Framework

A react framework is a library that is based on react adding other capabilities. Most of the time, they are web based server framework, adding routing and other web capabilities. They create a single...
React - Hydrate

hydrating a react page is a client side operation that happens on server-rendered markup (SSR) pages. The hydrate function: reads the HTML markup created with the React renderToString and build...
React - React-Snapshot

react-snapshot is not really a framework but a zero-configuration static pre-renderer running after the build of a Create React App See ...
React - Server Side Rendering (SSR) - DOM Server

This page is server side rendering (SSR) in React as opposed to the browser rendering. The server side rendering (SSR) functionality in React can output two types of pages: (that will become dynamic...
React - Styling

Styling a component in React. Traditional CSS-file-based styling with the import of stylesheet (with SASS, PostCSS, ..) SSR does not like it very much. See No Pseudo Classes/Element No Media...
React Framework - Next.js

Next is a React framework for server-rendered React applications. isomorphic apps (code that runs in the browser or in node) note from the getting started...
Web - Prerendering / Snapshoting (Dynamic to Static Web Site Generation)

Prerendering is a web static generator method that will take a dynamic website and turn it into a static web application. You then: don't need a server. improve the page load The website (called...



Share this page:
Follow us:
Task Runner