Everyone tells you that React is fast, virtual DOM is great, but it is just a haft of the truth. If you don’t follow the best practices for your React app, chance that you are slowing it down. React will be fast when you look deep inside and understand the rendering process. This article will show you the technique to bring out the best performance for your React app.

Find the slow component

React comes with a hidden powerful performance debugging tool. You can unlock it by adding ?react-perf into the app url. For example: http://localhost:3000?react-perf.

  • Open your app in browser and add ?react-perf at the end of url.
  • Open Chrome dev tool.
  • Click on Timeline tab
  • Click Record button and do some actions.
  • Click stop recoding button.
  • Check the User Timing section

Chrome dev tool will record every actions and with the aid from React, it will show exactly the rendering time for each component.

Now you know which component is slow and you can start apply optimizing technique to that component.

Use React.PureComponent

PureComponent is exactly similar to Component but there is one exception, it implement the shouldComponentUpdate by compare the new state and props with old state and props, it only renders when there is new change. Use PureComponent will give your app a small boost.

You can also implement shouldComponentUpdate if you want, but most of time, you don’t really it to do it.

Pass method to element correctly

This is how we usually pass a method to onClick event:

or

In the first case, you pass an arrow function into onClick event, so every time the render method is called, it always creates new anonymous function. So React recognizes the render result is different and it has to re-render the whole component again.

In the second case, the bind method always create new identity for doSomeThing method, so React still re-render our component.

Here is the recommendation:

Using the arrow function when creating doSomeThing method, you have already bind doSomeThing method into the scope of MyComponent and doSomeThing is always the same so our component doesn’t need to re-render it self.

Turn on production mode

Turn on the production mode can speed up our application up to 5 times, it also decreases bundle size, but it limits debug ability and type checking of our app.

Here is how you do it in Webpack:

Conclusion

You should avoid premature optimize your app. The best app is profile and check quick component is slow and optimize it.