Understanding the value of PureComponents in React

I’m just starting to get comfortable with the basics of React (creating and rendering components, updating state, passing props to children e.t.c.) and while reading through the docs came across PureComponent. Let’s take a look at what it is, and when you should/shoudn’t use it.

What is PureComponent?

In React, a PureComponent is exactly the same as a regular Component with one difference: a PureComponent automatically implements shouldComponentUpdate() with a shallow prop and state comparison. To understand what this really means, let’s take a look at shouldComponentUpdate() and shallow comparisons in JavaScript.

shouldComponentUpdate’s place in the React Lifecycle

React components go through a lifecycle, divided into three parts: creation, updating, and deletion. Obviously shouldComponentUpdate() falls into the updating category. shouldComponentUpdate() is available to us just before a component re-renders, and it allows us to compare old and new props and state. This is very valuable because to create a smooth user experience we only want our components to re-render when there is actually something new to display.

Shallow Comparisons

A shallow comparison is the comparison of primitive datatypes. shouldComponentUpdate() in a PureComponent will check and see for example that 1 equals 1, true equals true, and that references between objects and arrays are the same.

Perfomance Gains

shouldComponentUpdate() ’s quick check of a PureComponent’s old and new props and state before an update is super fast compared to an unnecessary re-render, especially if there are multiple children that would re-render without shouldComponentUpdate().

Be Careful

Because PureComponent’s shouldComponentUpdate() only shallowly compares props and state, it can produce false-negatives for complex data structures that require a deeper comparison. React’s docs recommend only using PureComponent when you’re working with simple, predictable props and state.

You also need to make sure when using PureComponent that all of its children are “pure”, otherwise shouldComponentUpdate() will skip prop updates for the whole component subtree.

Summary

React’s PureComponent provides some performance gains for your app provided that you a good understanding of what your props and state exactly are.

Show your support

Clapping shows how much you appreciated Jesse Tyner-Bryan’s story.