Demystifying the Pure Component
What? PureComponent again? That belongs to classes, and nobody uses classes anymore! How come you’re not writing about hooks?
Well, React hooks are very amazing and very useful – I definitely love ’em and will write about those soon. However, I am convinced that in even a year from now, people will still need the know-how of PureComponent and how it works. Even in his Resilient components article, which provides best practices and use cases for hooks, Dan Abramov is mentioning PureComponent’s work as a strategy and not necessarily as a specific React component.
Whether you’ve been doing React for 6 months or 2+ years or more, there’s no chance you’ve never at least heard of PureComponent.
That said, even after several years of React development, I found myself still having some questions about how exactly a PureComponent behaves.
Sure, most of us know it simply implements a shallow shouldComponentUpdate() comparison method and some of us have also learned to not just use PureComponent blindly in all cases. However, I still had doubts about how and when exactly its children are rendered, and under which conditions.
As I don’t like to guess around when it comes to tech / coding (or any other exact technical subject for the matter), I created an example for myself. And as it made things clear for me and for some of my colleagues, I was thinking why not clean it up, make it clearly readable and share it for others, so they could also have a clear understanding of how PureComponent works.
So here goes:
So, what do we have here?
We have a Parent – which is a Pure component. This parent is Pure but its props keep changing (due to the setInterval() which keeps modifying a state value) and so it keeps re-rendering.
The Pure Parent has children – one of them is Pure and the other isn’t. So one of them keeps re-rendering, and the other doesn’t. Really they are very similar and could be extracted to a more generalized form, but for the sake of this example we’ll keep it that way.
This example is quite simple and illustrates well how PureComponent handles props changes, and how it relates to its children. You can play with the code on the excellent StackBlitz platform to simulate more scenarios if you’d like.