Reputation: 323
The answer from this question makes sense: If the props for a child component are unchanged, does React still re-render it? and I also made a CodePen to verify it.
shouldComponentUpdate(nextProps, nextState) {
console.log(nextProps.test === this.props.test);
console.log('shouldComponentUpdate');
return true;
}
But one statement on React's website is that:
shouldComponentUpdate()
is invoked before rendering when new props or state are being received.
But in reality, shouldComponentUpdate()
is still invoked even if the props and state for a child component remain unchanged. Is there some mistake in the offical statement, or I have misunderstood it?
Upvotes: 4
Views: 1440
Reputation: 58002
Since the parent component Clock
is being rerendered every second, the Child
component also gets rerendered too. This is because Clock
rerenders completely whenever a state update happens, as the clock moving forward a second. Thus, since Child
is part of Clock
, it too get rerendered.
The quote from the React documentation is correct:
shouldComponentUpdate()
is invoked before rendering when new props or state are being received.
Whenever Child
is rerendered, the prop test
is received again and again after every second the Clock
is rerendered. That's what 'new props or state' is referring to here, not necessarily that it's getting different, unique props. Thus, shouldComponentUpdate
is called every time the Child
is rerendered because the prop test
is given to the Child
on each rerender.
Upvotes: 3