React Core & Hooks (407 Qs)•Part 9: React Hooks Deep Dive (262 - 316)
What is the purpose of renderToNodeStream method?
junior LevelCode ExampleHooks
The ReactDOMServer#renderToNodeStream method is used to generate HTML on the server and send the markup down on the initial request for faster page loads. It also helps search engines to crawl your pages easily for SEO purposes.
Note: Remember this method is not available in the browser but only server.
Code Example
tsx
import express from 'express';
import React from 'react';
import ReactDOMServer from 'react-dom/server';
import { App } from './App';
const server = express();
server.get('*', (req, res) => {
res.write('<!DOCTYPE html><html><head><title>SSR App</title></head><body><div id="root">');
// renderToNodeStream streams HTML chunks as they are generated
const stream = ReactDOMServer.renderToNodeStream(<App />);
stream.pipe(res, { end: false });
stream.on('end', () => {
res.write('</div><script src="/bundle.js"></script></body></html>');
res.end();
});
});