Chaitu Chaitu - 1 year ago 71
Javascript Question

Will react setState immedietly set the state?

I am trying to store a value using setState, however I am setting the state and in next line I am trying to console.log it, I am not able to see the value in the console.

getInitialState: function(){
myCountry: ""

var country =;
this.setState({"myCountry": country});
console.log(this.state.myCountry); //prints nothing

When I surfed for this I saw that setState is asynchronous, but I am not able to understand.

Ved Ved
Answer Source

You will not get the updated value of state just after calling setState(). This is because as soon as setState() is called view is re-rendered. So it is better to check the updated value inside render or add callback function to setState.

this.setState({"myCountry": country},function(){console.log(this.state.myCountry)});


render: function() {
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download