5

In the React lifecycle function shouldComponentUpdate(nextProps, nextState), nextProps is self explanatory.

But what does nextState do?

It doesn't sound right that I can evaluate upcoming state before even deciding if the component should be rendered/modified or not.

Fellow Stranger
  • 32,129
  • 35
  • 168
  • 232

2 Answers2

6

Basically the state is already changed at that point and do you deem it necessary to rerender the component and based on that you return true or false

mu_sa
  • 2,685
  • 10
  • 39
  • 58
5

nextState is for detecting if the component should update based on the upcoming state just like you mentioned.

This helps to optimize updating components. For example:

If state becomes a large object with several properties, but a specific component only cares about a single property or a small portion of the state, you can check for that change to determine if the component needs to re-render. This example was taken from the React documentation but does a good job of getting the point across:

shouldComponentUpdate(nextProps, nextState) {
    if (this.props.color !== nextProps.color) {
      return true;
    }
    if (this.state.count !== nextState.count) {
      return true;
    }
    return false;
}
Dan D
  • 2,493
  • 15
  • 23