The First And The Most Rewarding Step In Optimizing React App

React is usually fast, but there are situations when we need to make some optimizations to avoid performance issues.

Firstly, we need to understand in which cases React might get slow. When a component’s state changes, React has to calculate if it is necessary to update the DOM. It does this by comparing the old React elements to a new set of React elements. This process is called reconciliation. When there are a lot of elements to compare, like a big SVG file (here is an example), React provides us shouldComponentUpdate lifecycle method. This method allows your Component to exit the Update lifecycle if there is no reason to apply a new render.

1

Another way of using shouldComponentUpdate is to use React.PureComponent. React.PureComponent is similar to React.Component. The difference between them is that React.Component doesn’t implement shouldComponentUpdate(), but React.PureComponent implements it with a shallow prop and state comparison.

If you have functional component and your app is using at least React v16.6.0, you can use React.memo, which is a higher order component. It’s similar to React.PureComponent but for function components instead of classes.

2

If you have functional component and don’t want to transform it into a class-based component you can implement the shouldComponentUpdatelogic in a higher-order component (HOC) provided by recompose. It’s a functional utility belt for React, providing for instance the pure() HOC.

4

You can even be more specific and target only the props that you know may change, using recompose’s shouldUpdate()instead of pure().

3

The recompose library offers more performance HOCs, like onlyUpdateForKeys(), which does exactly the type of check from above checkPropsChang.

5

Recompose, beyond performance optimization, helps you extract data fetching logic, HOC composition, and props manipulation in a functional and testable way.

Notice: Use PureComponent and shouldComponentUpdate only when you need to, as described in the beginning of the article.

Leave a comment