Why use React.PureComponent ?
PureComponent is one of the lesser known apis built into React. Today let's see what it does and common cases of when to use it.
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.
It's a performance optimization technique. Luckily its simple to implement. Let's see an example:
I create two components Parent
and Child
.
Parent has a state of counter
and message
. It renders Child
and passes message
as a
prop to it.
See the code below:
I used class components for the sole reason to console.log how many times
each component will render.
If you run this example you will notice that both logs "parent render" & "child render" are
run EVERYTIME we update the state by incrementing the counter on Parent
.
However, message
never changes. So there is no reason for Child
to be re-rendered
every time. This is where PureComponent comes into play.
Switch Child
to extend PureComponent
.
PC will make a shallow comparison of props and state. If they have not changed - no
re-render will occur.
Try to run the same example - you will see when updating the counter
- only Parent
logs -
Child
is not logging anymore as it is not changing.
The difference in this example is tiny and won't make a difference but in scenarious when
Parent
renders multiple children it might be worth to implement.
Thank you!