Comprehensive Guide to React Server-Side Rendering (SSR) with Code Examples

This article provides an in‑depth tutorial on implementing server‑side rendering (SSR) for React applications, covering basic concepts, Koa server setup, ReactDOMServer APIs, routing with react‑router, Redux state hydration, CSS handling, performance optimizations, and modern SSR frameworks such as Next.js and Umi.

Sohu Tech Products
Sohu Tech Products
Sohu Tech Products
Comprehensive Guide to React Server-Side Rendering (SSR) with Code Examples

This article explains the fundamentals of server‑side rendering (SSR) for React, starting with the motivation for SSR such as faster first‑paint and SEO benefits, and contrasts it with client‑side rendering.

It shows how to create a simple Koa server that uses react-dom/server to render a React component to an HTML string:

// server.js
import Koa from 'koa';
import { renderToString } from 'react-dom/server';
import React from 'react';
import Home from './containers/Home';

const app = new Koa();
app.use(async ctx => {
  const content = renderToString(<Home />);
  ctx.body = `
    <html>
      <head><title>SSR Demo</title></head>
      <body><div id="root">${content}</div></body>
    </html>`;
});
app.listen(3001);

The guide then introduces routing with react-router and StaticRouter, demonstrating how to match routes on the server and render the appropriate component tree.

import { StaticRouter } from 'react-router-dom';
import { renderRoutes, matchRoutes } from 'react-router-config';

const content = renderToString(
  <StaticRouter location={ctx.path} context={context}>
    {renderRoutes(Routes)}
  </StaticRouter>
);

For state management, it details how to set up a Redux store that can be created both on the server and client, and how to hydrate the client store with the server‑generated state using a window.__INITIAL_STATE__ script.

// store.js (client)
export const getClientStore = () => {
  const preloaded = window.__INITIAL_STATE__ || {};
  return createStore(rootReducer, preloaded, applyMiddleware(thunk));
};

// store.js (server)
export const getServerStore = () => createStore(rootReducer, applyMiddleware(thunk));

To fetch data before rendering, the article adopts the React‑Router loadData pattern: each route can define a loadData function that dispatches async actions, and the server awaits all promises before calling renderToString.

// routes.js
{ path: '/about', component: About, loadData: store => store.dispatch(fetchAbout()) }

// server handling
const promises = matchRoutes(Routes, ctx.path)
  .filter(r => r.route.loadData)
  .map(r => r.route.loadData(store));
await Promise.all(promises);

CSS handling is covered using isomorphic-style-loader so that styles are collected during server rendering and injected into the <head> to avoid flash‑of‑unstyled‑content (FOUC).

// webpack.server.js
{ test: /\.css$/, use: ['isomorphic-style-loader', 'css-loader'] }

// server.js
const css = new Set();
const insertCss = (...styles) => styles.forEach(s => css.add(s._getCss()));
const html = `
  <html>
    <head>
      <style>${[...css].join('
')}</style>
    </head>
    <body>...</body>
  </html>`;

Finally, the article mentions modern SSR frameworks such as Next.js, UmiJS, and Ice.js that provide out‑of‑the‑box SSR support, and briefly introduces newer React APIs like useId and server‑side Suspense for incremental hydration.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

frontendReduxReactNode.jsSSRwebpackServer-side Rendering
Sohu Tech Products
Written by

Sohu Tech Products

A knowledge-sharing platform for Sohu's technology products. As a leading Chinese internet brand with media, video, search, and gaming services and over 700 million users, Sohu continuously drives tech innovation and practice. We’ll share practical insights and tech news here.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.