The ReactDOMServer module in the React ecosystem facilitates the rendering of React components into static HTML. While it’s typically associated with server-side operations, especially in Node.js environments, its methods can also be used in client-side scenarios.
Server-side rendering is a technique where the server pre-renders a web page’s content before sending it to the browser. This has several benefits:
There are two primary methods provided by ReactDOMServer:
For instance, when operating a Node-based web server such as Express, Hapi, or Koa, you typically use the renderToString method to convert your main component into a string format and then send it as a response.
Express.js is a popular Node.js framework used for building web applications. By integrating ReactDOMServer, one can easily serve pre-rendered React content. Below is a simple example:
// using Express
import { renderToString } from 'react-dom/server';
import MyPage from './MyPage';
app.get('/', (req, res) => {
res.write('<!DOCTYPE html><html><head><title>My Page</title></head><body>');
res.write('<div id="content">');
res.write(renderToString(<MyPage />));
res.write('</div></body></html>');
res.end();
});
ReactDOMServer offers a robust way to harness the power of server-side rendering in React applications. Whether you’re looking to improve performance, SEO, or deliver a consistent user experience, SSR with ReactDOMServer is a tool worth considering.
You may also like the article about React component re-rendering on browser resize to understand how components respond to viewport changes.