Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Prevent react-router re-creating component when switching links

I have a number of nav links at the top level that switch page level components in and out when you switch between the links. Some pages have complex grid components that are expensive to create. I noticed that react-router constructs the component every time a page is switched. Is there a way to cache the component passed into a route?, i.e PositionsPage

<Route path="/positions" component={PositionsPage} />

like image 777
marchaos Avatar asked Oct 30 '22 23:10

marchaos


1 Answers

This is a very important performance consideration in React as a whole (and not just react-router).

By default design, React re-renders the complete DOM tree for any change in props or state.

Here is a summary of techniques that the React documentation for Advanced Performance suggests.

Use the production build

NOTE: Correctness of components is automatically taken care of. Nothing to worry.

This should be fairly simply. The following webpack.config.js plugins section snippet should make sure that the NODE_ENV variable reaches the React source code.

  ...
  plugins: [
    new CommonsChunkPlugin('bundle.js'),
    new webpack.DefinePlugin({
      'process.env': {
        'NODE_ENV': JSON.stringify(process.env.NODE_ENV)
      }
    })
  ]
  ...

Now just ensure the NODE_ENV=production webpack -p.

This ensures that all those warnings/errors and propTypes checking is skipped.

Avoiding reconciling the DOM

WARNING: You must handle all possible condition matrices (if needed) of props and state to make sure you don't mess up the correctness of rendering.

This is the callback signature which must be implemented. This is called whenever any state or prop value changes.

shouldComponentUpdate: function(nextProps, nextState) {
  // @TODO your logic here
  // return true to update, false otherwise
  return true;
}

Keep in mind that React will invoke this function pretty often, so the implementation has to be fast.

like image 115
activatedgeek Avatar answered Nov 09 '22 13:11

activatedgeek