The simple answer to your question will be "Yes", but for one update cycle. Let me explain this.
As you may already know React setState
does not always immediately update the component. Sometimes React batch or defer the updates until later. As an example, let's assume you have something like follows in your event handler.
onClick() {
this.setState({quantity: state.quantity + 1});
this.setState({quantity: state.quantity + 1});
this.setState({quantity: state.quantity + 1});
}
These state update will be queued and execute all together in one update cycle. In such scenario React only create a new state object for the first setState
and that object will mutate for subsequent setState
updates. You can clearly see this in the source code here.
However, this is something totally about how React works under the hood and we won't need to worry about that. Because there will be only one shouldComponentUpdate()
and componentDidUpdate()
for one cycle. By the time we access the state
it will be always a new object. So we can safely assume that setState() guaranteed to create a new state object every time. But make sure that you aware of other implications of setState
which explains in the official documentation.
I'd like to know whether this.state !== nextState
is always guaranteed
to be true inside shouldComponentUpdate()
.
The answer to your this question will be "No" as also explained in other answers. shouldComponentUpdate()
will be called because of either state change, props change or both. So this.state !== nextState
won't true if the component has updated only because of props change.