Sub topic 2
Turning components into HTML
This chapter assumes you can write function components with useState and useEffect, run a small Express server, and build JSX with a bundler. Here you will turn a React tree into an HTML string on the server with renderToString. You will also learn what that string contains, what it leaves out, and where the method stops being enough.
What renderToString does
renderToString comes from react-dom/server. It takes a React element and returns an HTML string. React runs your components from the top down, collects the elements they return, and writes each one out as markup.
The render is a single synchronous pass. Each component function runs once, and the result is a finished string. No tree stays in memory afterward, so the server holds nothing that the browser could later reuse. The browser has to rebuild its own copy of the tree. That step is hydration, covered in the next chapters.
A worked example
Start with a component that uses state, an effect, and an event handler.
import { useEffect, useState } from 'react';
export default function Counter({ start }) {
const [count, setCount] = useState(start);
useEffect(() => {
document.title = `Count ${count}`;
}, [count]);
return (
<button onClick={() => setCount(count + 1)}>
Clicked {count} times
</button>
);
}Now render it from an Express route and place the result in a page template.
import express from 'express';
import { renderToString } from 'react-dom/server';
import Counter from './Counter.js';
const app = express();
app.use('/static', express.static('dist'));
app.get('/', (req, res) => {
const props = { start: 3 };
const html = renderToString(<Counter {...props} />);
const serializedProps = JSON.stringify(props).replace(/</g, '\\u003c');
res.status(200).type('html').send(`<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<title>Counter</title>
</head>
<body>
<div id="root">${html}</div>
<script>window.__PROPS__ = ${serializedProps};</script>
<script src="/static/client.js"></script>
</body>
</html>`);
});
app.listen(3000);The value of html for this component is:
<button>Clicked <!-- -->3<!-- --> times</button>Three details in that output matter in practice.
- The state is the initial value.
useState(start)returned3, and the markup shows3. - There is no
onClick. An HTML string cannot carry a JavaScript function. The button is visible but does nothing until client code attaches the handler. - React added
<!-- -->comments. They separate adjacent text pieces ("Clicked ",3, " times"). Without them the browser would merge the pieces into one text node, and React could not match its own text nodes against the DOM later. Do not strip these comments out of the output.
What runs on the server and what does not
The server render runs your component bodies. It does not run everything the client does.
| Part of a component | Runs during `renderToString`? |
|---|---|
| Function body and JSX | Yes, once |
| `useState` initializer | Yes, returns the initial value |
| `useReducer`, `useMemo`, `useId` | Yes |
| `useEffect` callbacks | No |
| State updates such as `setCount` | Not applicable, because there is no second render |
| Event handlers like `onClick` | Never called, and not written into the HTML |
| Browser globals such as `window` and `document` | Not available |
The last row is the most common source of crashes. This component works in the browser but throws on the server with ReferenceError: window is not defined:
function Width() {
return <p>Width: {window.innerWidth}</p>;
}Reading window during render is also unsafe for a second reason. Even if you guard it with typeof window !== 'undefined', the server and browser would then produce different output, which causes a hydration mismatch. Later chapters cover that. For now, treat the render phase as code that must produce the same output in both environments, and put browser-only work in effects.
Escaping and embedding data
React escapes text content and attribute values when it writes HTML. A string like <script>alert(1)</script> placed inside {...} becomes harmless text. That protection covers only what React renders. Anything you concatenate into the template yourself is your responsibility.
The example above passes the props to the browser through a <script> tag. A plain JSON.stringify is unsafe there. If a value contains </script>, the browser ends your script block early and treats the rest as markup. Replacing every < with \u003c keeps the JSON valid while removing the risk. For anything beyond small data, use a serializer library built for this purpose.
Limits of renderToString
renderToString is the simplest server API, which makes it a good first step. It has three limits that explain why the later chapters introduce streaming.
- It blocks. The render is synchronous, so the Node.js event loop handles no other request until it finishes. A large tree or a slow component delays every other user.
- It sends nothing early. The response begins only after the whole string exists. The browser shows no content until the slowest part of the page is done.
- It cannot wait for data. If a component suspends, because it is waiting for data or a lazy import,
renderToStringdoes not wait. It writes the nearest Suspense fallback into the HTML. The real content is then rendered in the browser after the JavaScript loads. You get the fallback in the HTML and a client-side render for that part, so that part loses the benefit of server rendering.
The second and third limits are the reason renderToPipeableStream exists. It can send the page's shell first and fill in suspended parts as their data arrives. You will build that in the streaming chapters.
The browser also does not wait for your script to run before showing the HTML. The user sees the button as soon as the HTML arrives, which is the main benefit of server rendering. But the page is inert until client.js loads and hydrates it. That gap between visible and interactive is the cost to keep in mind in the next chapter.
Common errors
window is not definedordocument is not defined. A component touched a browser global during render. Move the access intouseEffect, or provide a server-safe value.- A blank
<div id="root"></div>. You forgot to put the string into the template, or you rendered a different element than the one the client expects. Objects are not valid as a React child. You returned a plain object or a Promise from a component. This fails the same way on the server and the client.- A mangled page after the script tag. Unescaped JSON containing
</script>, as described above. - Importing the server renderer in client code.
react-dom/serveris large and meant for Node.js. Keep it out of the browser bundle.
Exercise
Your Express route calls renderToString(<Profile />). Profile reads localStorage.getItem('theme') directly in its function body. What happens, and where should that read go instead?
Show answer
The server render throws ReferenceError: localStorage is not defined, because Node.js has no localStorage. Even with a guard that skips the read on the server, the server HTML and the first browser render would differ, which causes a hydration mismatch. Read the value inside useEffect and store it in state. Both environments then render the same default first, and the browser applies the saved theme after it hydrates.
Exercise
A component renders <p>Total: {total} items</p> with total equal to 12. The HTML from renderToString contains <!-- --> twice inside the paragraph. Why, and is it a bug?
Show answer
It is not a bug. The paragraph holds three adjacent text pieces: "Total: ", the number 12, and " items". React inserts empty comment nodes between them so the browser keeps them as separate text nodes. That lets React match its own text nodes against the DOM when it hydrates. Removing the comments would break that matching.