Anna Lee
Anna Lee

Reputation: 951

React PureComponent and shouldComponentUpdate

I know about PureComponent, but from the deep thought, I got confused about it.

ShouldComponentUpdate function is invoked when state or props are changed. So, we definitely know that something in state or props are changed if ShouldComponentUpdate is invoked. And those changes should be reflected in component view also. If state or props are not changed, shouldComponentUpdate is never called.

The PureComponent provides shallow comparison between old state or props and new state or props and if they are identical, it does not render. But we already know that the fact that shouldComponentUpdate is called means that new state or props are not same as old state or props.

Logically, I am confused about it so I got to post this question. Could you please give some advice for it?

Upvotes: 1

Views: 1968

Answers (1)

Jayce444
Jayce444

Reputation: 9063

NOTE: this is my understanding, so others please feel free to comment any issues/corrections

You've made an incorrect assumption in your question. You think for a plain React.Component that if nothing has changed in state/props then shouldComponentUpdate is never called and it won't re-render. That's not true, for example if a plain component's parent re-renders and that parent passes props to the child, the child will re-render too. Even if those prop values that it's passing are actually the same (you can test this by putting a console.log in the child's render() function). However, even though the child will re-render, nothing will actually change (in terms of the DOM) since the props are the same. So technically it did an unnecessary re-render.

In a plain component, shouldComponentUpdate always returns true (assuming you haven't explicitly defined it). So if the props/state are the same it will always re-render, it's just that if there aren't any pertinent differences, the DOM won't change in any way. However, in a PureComponent it will actually do a shallow comparison of the new state/props, and only trigger a re-render if they've changed. The idea is that it implements a shouldComponentUpdate method for you.

For components that don't often want to change, doing this shallow comparison (which is relatively quick and cheap) is better than constantly just re-rendering regardless of any changes. To summarise, pure components prevent unnecessary re-renders by doing comparisons of state/props before re-rendering, and making sure they're actually different.

Upvotes: 3

Related Questions