renderToString
renderToString synchronously renders a React tree to an HTML string. This is a legacy API that does not support Suspense or streaming.
Reference
renderToString(element, options?)
Renders a React element to an HTML string with React-specific attributes like data-reactroot.
Parameters
element:ReactNode- The React element to renderoptions:Object(optional)identifierPrefix:string- Prefix for IDs generated byuseId. Useful for avoiding conflicts when using multiple roots on the same page.
Returns
Returns astring containing the rendered HTML with React attributes.
Caveats
Usage
Basic server-side rendering
Using with Express
- Node.js
- Edge Runtime
Setting identifier prefix
UseidentifierPrefix to avoid ID conflicts when rendering multiple React roots on the same page:
Handling errors
renderToString throws errors synchronously, so use try-catch:
Limitations
No Suspense Support
If your component tree contains aSuspense boundary with a component that suspends, renderToString will throw an error:
renderToPipeableStream or renderToReadableStream which fully support Suspense.
Blocking Rendering
renderToString must render the entire component tree before returning:
Performance Considerations
renderToString is synchronous and blocks the event loop:
Migrating to Modern APIs
If you’re usingrenderToString, consider migrating to modern streaming APIs:
- Before (renderToString)
- After (renderToPipeableStream)
Runtime Availability
renderToString is available in multiple runtime exports:
- Node.js
- Edge
- Browser
ReactDOMLegacyServerNode implementation.Common Issues
Suspense error: does not support Suspense
Suspense error: does not support Suspense
renderToString cannot handle Suspense boundaries. Remove Suspense or migrate to renderToPipeableStream/renderToReadableStream.Hydration mismatch warnings
Hydration mismatch warnings
Ensure server and client render identical HTML. Common causes:
- Using
Date.now()orMath.random()during render - Different data on server vs client
- Browser-specific APIs used during render
Memory leaks with large renders
Memory leaks with large renders
renderToString builds the entire HTML string in memory. For very large pages, this can cause memory issues.Solution: Use streaming APIs which write directly to the response stream without buffering.See Also
renderToStaticMarkup- Render without React attributesrenderToPipeableStream- Modern streaming API for Node.jsrenderToReadableStream- Modern streaming API with Web Streams- Server Rendering Overview - Compare all server rendering approaches