Using a <PureComponent/> in React
Occasionally I hear about Reacts PureComponent
, but I did not realize the simple mistake I was making by not taking advantage of this great tool. Lets take a look at the following React Code.
This is a fairly simple project, it stores and displays a history of everything that you have typed into the input.
Now that you have read over and understand the above project lets take a look at a GIF of this project in action. Its important to note that this GIF has “Highlight Updates” turned on in the React Dev Tools. This allows us to see when the component is being updated (aka re-rendered).
Note that every time we type in the Input every single <Message/>
component is being re-rendered. This is a big no-no. Imagine the consequences on a list of several hundred items that were more complicated, performance would be terrible.
There are a few solutions to this, but to make this short we can summarize your options as Do It Yourself or Let React Do It For You.
First I am going to show you how you can do it yourself using shouldComponentUpdate()
. This is a fairly simple process for this component but can get increasingly complicated as your project grows and components get more complicated. Lets take a look at the gist below.
The above example checks if the message has been updated. If it has not the component will not re-render. This is a fairly simple and easy example, but there is an even easier thanks to the React Team. Lets take a look at the gist below that uses PureComponent
.
The only change we have made to the above component, compared to our original example, is replace Component
with PureComponent
. Lets look at the GIF below to see how this has impacted our rendering and re-rendering.
Notice how we have eliminated the need to now re-render every single <Message/>
component every time we type and a new message is stored and displayed.
This works because PureComponent
implements a shallow comparison for us by default in shouldComponentUpdate()
, saving us time and reducing the complexity of our components. Its important to note that the comparison is shallow, meaning that if you are updating an object with nested values the component will not re-render as React has not noticed a change.
Extra Reading
PureComponent: Check this out before you use PureComponent
and make sure you fully understand the docs. Its a super short read.
shouldComponentUpdate: For when PureComponent
just does not cut it you will need to understand how shouldComponentUpdate()
works.
If you enjoyed this article please feel free to follow me for periodic articles on Javascript, React, and general Web Development.
You can also find me on twitter!
Thanks for reading! :)