React PureComponent

May 12, 2017

There's a lot of ways for creating React components, one of these methods is using a "Pure" component. This new component was released on June 29, 2016 in v15.3 which replaces it's predecessor pure-render-mixin.

PureComponent is one of the most significant ways to optimize React applications because is easy and fast to implement. The usage of PureComponent gives a considerable increase in performance and it reduces the number of render operations in our application. PureComponent changes the life-cycle method shouldComponentUpdate and adds some logic to automatically check whether a re-render is required for the component. This allows a PureComponent to call method render only if it detects changes in state or props.

if (this.state.someVal !== computedVal) {
  this.setState({ someVal: computedVal })
}

PureComponent saves us time and helps us to avoid writing redundant code. It's important to understand the right ways to use it, otherwise its usefulness is voided. A PureComponent will always re-render if the state or props reference a new object. This implies that if we do not want to lose the benefits of PureComponent, we should avoid such structures:

<MyCoolList values={this.props.values || []} />

In fact, the transition to PureComponent is quite simple, if you are aware of peculiarities of the shallowEqual and JS itself. Normally, the migration as simple as changing the base class from:

class MyComponent extends Component {...}
to
class MyComponent extends PureComponent {...}

If you want to see a simple example of using PureComponent, please check this codesandbox demo. On the first example we have a ReactHighcharts component which will re-render his chart data on each counter state update, so click in the button and see how the chart is render on update. In the second example whe move our ReactHighcharts to a React PureComponent, this wont re-render if the counter state changes on parent component, so click in the button and see how the chart dont reflow, also click in the button "Set New Data" for update chart data in the second example.