reactjs / server-components-demo

Demo app of React Server Components.
https://reactjs.org/server-components
MIT License
4.27k stars 639 forks source link

Suggestion: renderReactTree performance improvement #41

Open arnaudbzn opened 3 years ago

arnaudbzn commented 3 years ago

In renderReactTree the following block of code is only required once at runtime:

 await waitForWebpack();
 const manifest = readFileSync(
    path.resolve(__dirname, '../build/react-client-manifest.json'),
    'utf8'
 );
 const moduleMap = JSON.parse(manifest);

In the current example, the performance impact is minor but with a large number of components, doing this treatment for each server request can have bigger impact.

A quick optimization below:

let moduleMap;

async function renderReactTree(res, props) {
  if (!moduleMap) {
    await waitForWebpack()
    const manifest = readFileSync(
      path.resolve(__dirname, '../build/react-client-manifest.json'),
      'utf8'
    );
    moduleMap = JSON.parse(manifest);
  }
  pipeToNodeWritable(React.createElement(ReactApp, props), res, moduleMap);
}

The NextJS demo is optimized: https://github.com/vercel/next-server-components/blob/master/libs/send-res.js