2

I understand that nextProps and nextState are used in shouldComponentUpdate to determine if the component should rerender or not based on the result of comparing this.state.someProperty to nextState.someProperty. If they are different, the component should rerender.

That is clear.

However, this does not seem to be what is happening. View this code.

    class Box extends React.Component {

  constructor(props) {
    super(props);
    this.state = {
      count: 0
    }

   this.counter = 
     this.counter.bind(this)
  }

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})
    }, 10000);
  }

  componentDidMount() {
    this.counter();
  }

  shouldComponentUpdate(nextProps, nextState) { 
    console.log(this.state.count + " " +  nextState.count)
    return true;
  }

  render() {
    return (
      <div> 
        <h1>This App Counts by the Second </h1>
        <h1>{this.state.count}</h1> 
    </div>
    );
  }
};

In shouldComponentUpdate, I am logging both the state.count and nextState.count values, and they are equivalent each time. Should they not be different? If not, what is the purpose of checking to see if they are equivalent if changing the state with setState ensures that they are the same?

WriterState
  • 359
  • 3
  • 18

1 Answers1

5

nextState and currentState are both always the same,because you have mutated the original state object while updating it

  counter() {
    setInterval(()=>{
      this.setState({count: this.state.count+=1})  // mutation done here
    }, 10000);
  }

In order to solve this issue, you must use functional setState like

counter() {
    setInterval(()=>{
      this.setState(prevState => ({count: prevState.count + 1}))
    }, 10000);
  }
Shubham Khatri
  • 270,417
  • 55
  • 406
  • 400
  • Thank you! In your example, where is the prevState variable being defined? Where does it come from? Is this something that is passed from setState? – WriterState Oct 17 '18 at 05:17
  • Wouldn’t `this.state.count+1` also work? Just remove the mutating += from the statement – Sami Kuhmonen Oct 17 '18 at 05:23
  • 1
    @SamiKuhmonen, yes it would work, but its recommended to use functional setState when updating current state based on the previous one to avoid any inconsistencies. That is the reason I suggested the above answer – Shubham Khatri Oct 17 '18 at 05:28
  • 1
    @SamiKuhmonen You can read this answer for more details https://stackoverflow.com/questions/48209452/when-to-use-functional-setstate/48209870#48209870 – Shubham Khatri Oct 17 '18 at 05:28
  • @WriterState, Please check the link inmy above comment to know more on how it works and also check the documentation of setState – Shubham Khatri Oct 17 '18 at 06:13