ReactJS :: Server rendering

With large applications, users can be looking at a blank screen while the site loads in. Ideally this should be as small as possible. By rendering the initial view on the server, the perceived load time can be reduced, which comes with the added benefit of enabling crawlers to more easily parse content.

React is already equipped to handle rendering on Node servers. A special version of the DOM renderer is available, which follows the same pattern as on the client side. 

import ReactServer from 'react-dom/server';
import App from './App';
[...]
ReactServer.renderToString(<App />);

This method will output the regular HTML as a string, which can then be placed inside a page body as part of the server response. On the client side, React detects the pre-rendered content and seamlessly picks up where it left off.

Server rendering in applications that use code splitting, routing or state containers can get more complicated, but it is still possible. Redux, for example, will build a preloaded state object on the server, which can hydrate the client side when creating the store. 

Leave a Reply

Your email address will not be published. Required fields are marked *

*