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} />
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.
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With