What does nextState do in shouldComponentUpdate?
Asked Answered
P

2

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.

Philipp answered 5/2, 2018 at 0:48 Comment(0)
E
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

Exemplar answered 5/2, 2018 at 1:17 Comment(0)
A
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;
}
Alas answered 5/2, 2018 at 0:56 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.