Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Can someone explain how this state update is resolved?

Hi I’ve been learning ReactJs and I wrote these lines:

  handlerClick(i) {
    this.setState(
      (state) => (state.squares = [...state.squares, (state.squares[i] = "X")])
    );
  }

Now, I know whats happening but I’m confused with how this is working, the order that each operation is being executed…

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Regarding the order of operations, everything to the right of an assignment operator is evaluated before the assignment takes place, so every usage of state in the expression to the right of =, refers to state before any assignment occurs.


Regarding proper usage of setState, you shouldn’t assign to your old state, but rather return an entirely new object:

handlerClick(i) {
  this.setState((state) => {
    const squares = [...state.squares];
    squares[i] = "X";
    return {...state, squares };
  });
}

Or, equivalently:

handlerClick(i) {
  const squares = [...this.state.squares];
  squares[i] = "X";
  this.setState({...this.state, squares});
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading