dmcshehan
dmcshehan

Reputation: 1269

weird question about shouldComponentUpdate()

I don't understand how shouldComponentUpdate() method has access to old state, As i know, shouldComponentUpdate() is fired after props or state changes.

Suppose you call setState() , After that the current state will be changed and will be update with new state. But shouldComponentUpdate() is fired even after updating the state to the latest version. Therefore how can 'this.state' inside shouldComponentUpdate() return the old state?

shouldComponentUpdate(nextProps, nextState) {
   console.log(this.state); // how can this be old state?
}

Did anyone get an idea? Thanks a lot.

Upvotes: 1

Views: 457

Answers (2)

Nazim
Nazim

Reputation: 367

This lifecycle function is called before anything on the component gets updated including state like the react docs emphasizes.

shouldComponentUpdate() is invoked before rendering when new props or state are being received.

So at the moment in time where shouldComponentUpdateis called, the new state has not been applied yet and this.state still points to the old state.

Upvotes: 3

H S
H S

Reputation: 735

The simplest way to put this would be - a render is triggered while something has changed above an element, in hierarchy. If the component itself will render during this render cycle initiated from above, is dependent on the return value of shouldComponentUpdate.

If this method returns true, the render will happen changing the component's current state, which was not changed until the shouldComponentUpdate returned true.

Hence this.state inside shouldComponentUpdate method has older state and nextState in the arguments has latest state.

Upvotes: 2

Related Questions