reactjs: Does setState() immediately change this.state?

I've experimented some cases in which calling this.setState({ foo: true }) and immediately checking this.state.foo does not return the new value true.

I can't tell now the exact case in which this happens (maybe when calling multiple times to setState() in the same iteration, I don't know). So I wonder:

Does reactjs guarantee that the following will always work?

this.setState({ foo: true });

console.log(this.state.foo);
// => prints true

Upvotes: 1

Views: 86

Answers (2)

user5738822
user5738822

Reputation:

It's done asynchronously. So you may not see the update within the method. Check that in componentDidUpdate. or you can see the result in the setState callback , like this :

this.setState({name: nextProps.site.name} , ()=>{

console.log(this.state.name);

});

Upvotes: 0

Oleksandr T.
Oleksandr T.

Reputation: 77482

Does reactjs guarantee that the following will always work?

No, setState is asynchronous method., if you want to get updated state you should use callback as second argument

this.setState({ foo: true }, () => {
  console.log(this.state.foo);
});

Upvotes: 5

Related Questions