Sub topic 2
Turning components into HTML
This chapter covers how React converts a component tree into an HTML string on the server. It assumes you know function components, props, and state, and that you can run a basic Node.js and Express server with a bundler that handles JSX.
What rendering to HTML means
On the client, React builds DOM nodes and inserts them into the page. On the server there is no DOM. React instead walks your component tree and writes out the HTML text those components describe. The browser receives that text and can show it before any JavaScript has loaded.
React's react-dom/server package provides the functions that do this. The simplest one is renderToString. It takes a React element and returns one complete HTML string.
A first example with renderToString
import express from 'express';
import { renderToString } from 'react-dom/server';
function Greeting({ name }) {
return <h1>Hello, {name}</h1>;
}
const app = express();
app.get('/', (req, res) => {
const html = renderToString(<Greeting name="Ada" />);
res.send(`<!DOCTYPE html><html><body><div id="root">${html}</div></body></html>`);
});
app.listen(3000);The string produced for Greeting is <h1>Hello, Ada</h1>. You wrap it in a full document and send it. Open the page with JavaScript disabled and the heading still appears.
What runs during a server render
The server render runs your component functions from top to bottom. It does not run everything.
| Runs on the server | Does not run on the server |
|---|---|
| Component function bodies | `useEffect` callbacks |
| Initial `useState` values | Event handlers such as `onClick` |
| Props and context reads | Browser APIs such as `window` and `document` |
The output is a snapshot of the first render. State updates, effects, and clicks have no meaning yet, because nothing is interactive until the browser attaches React to the HTML.
The flow from request to HTML
Limits of renderToString
renderToString is easy to use, but it has costs you should know about.
- It is synchronous in the sense that it returns only when the whole tree is done. If one component is slow, the user waits for everything.
- It does not wait for data. A component that suspends is rendered as its fallback, and React finishes the content on the client.
- It does not support streaming, so the server cannot send the top of the page early.
Later chapters replace it with renderToPipeableStream, which sends HTML in pieces and works with Suspense. For small pages and for learning the model, renderToString is still a clear starting point.
Common errors
window is not defined: browser-only code ran during render. Move it intouseEffect.- Blank page in the browser: you returned the HTML string without wrapping it in a document, or you forgot
res.send. - Page looks right but buttons do nothing: this is expected. The HTML is static until hydration, which a later chapter covers.
Exercise
A component calls localStorage.getItem('theme') directly in its function body. It works in the browser, but the server throws an error when you call renderToString. Why does this happen, and where should the call go?
Show answer
Node.js has no localStorage, so the call fails during the server render. Move it into a useEffect callback, which runs only in the browser after the page loads, and store the result in state.