5
votes

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.

2

2 Answers

6
votes

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

5
votes

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;
}