Home > Blockchain >  setState updates asynchronously
setState updates asynchronously

Time:05-18

I am refering to the comment below from: https://reactjs.org/docs/state-and-lifecycle.html


State Updates May Be Asynchronous

React may batch multiple setState() calls into a single update for performance.

Because this.props and this.state may be updated asynchronously, you should not rely on their values for calculating the next state.

For example, this code may fail to update the counter:

// Wrong
this.setState({
  counter: this.state.counter   this.props.increment,
});

To fix it, use a second form of setState() that accepts a function rather than an object. That function will receive the previous state as the first argument, and the props at the time the update is applied as the second argument:

// Correct
this.setState((state, props) => ({
  counter: state.counter   props.increment
}));

I am not quite sure what it means. And I found the examples confusing.

So I came up with an example of my own.

If I understand the comments above correctly, then the following not correct?

const [var, set_var] = useState(false);

...

set_var(!var)

I am attempting to set the new state using the value of the current state.

According to the tutorial, this is not correct?

CodePudding user response:

It is correct, but there are some cases where it might not work as you expect.

For examlpe, if you use it twice

const [var, set_var] = useState(false);

set_var(!var);
set_var(!var);

would you expect it to go false->true->false ? Because it will not. It will go false->true->true because in the second call the var will not have been updated, and so it will again use !false.

Using the callback form, that will work with the current value of the variable at the moment of the callback execution it will work as expected.

set_var( prevVar => !prevVar )
set_var( prevVar => !prevVar )

this will indeed change it twice and end to false again

  • Related