renderToString
Renders a React tree to an HTML string synchronously on the server.Reference
renderToString(reactNode, options?)
Call renderToString to render your app to HTML on the server.
/src/server/ReactDOMLegacyServerNode.js:18-28
Parameters
ReactNode
required
A React node you want to render to HTML. For example, a JSX element like
<App />.ServerOptions
Optional server rendering options.
Returns
string
An HTML string with React-specific attributes like
data-reactroot. This HTML can be sent to the client and hydrated with hydrateRoot.Usage Examples
Basic Server Rendering
With Client-Side Hydration
Server:With Express and Template
With Next.js (Legacy)
Limitations
Does Not Support Suspense
renderToPipeableStream instead:
Synchronous and Blocking
renderToString is synchronous and blocks the Node.js event loop until rendering completes. This can cause performance issues for large apps.
No Streaming
Client must wait for entire HTML string before anything renders:Migration Guide
From renderToString to renderToPipeableStream
Before:Benefits of Migration
- Suspense Support - Async components work properly
- Streaming - HTML sent to client as it’s generated
- Better Performance - Non-blocking, scales better
- Selective Hydration - Interactive sooner on client
- Error Handling - Better error recovery
When to Use renderToString
Despite being legacy,renderToString is still useful for:
- Static Site Generation - Pre-rendering at build time
- Email Templates - Generating HTML emails
- Testing - Simple HTML output for snapshots
- Simple Apps - No Suspense, small scale
Static Site Generation Example
TypeScript
Error Handling
Performance Considerations
Measure Rendering Time
Optimize Large Apps
Common Pitfalls
Don’t use browser APIs
Don’t forget to escape user content
Related APIs
- renderToStaticMarkup - Render without React attributes
- renderToPipeableStream - Modern streaming SSR (Node.js)
- renderToReadableStream - Modern streaming SSR (Web Streams)
- hydrateRoot - Hydrate server-rendered HTML