12

The state loggedIn here is updating perfectly because I am changing a button depending on the state. But whenever I am logging in console the value of logged in state immediately after changing it, it shows the opposite. So if the loggedIn just because true it still shows false in console. What is the reason behind it?

constructor(props) {
    super(props);
    this.state = {
        loggedIn: false
    }
}
changeState(val){
    this.setState({
        loggedIn: val
    });
    console.log(this.state.loggedIn);
}
render() {
    return (
        this.state.loggedIn ?  <Home_user onUpdate={(e) => this.changeState(e) } /> : <Auth onUpdate={(e) => this.changeState(e) } />
    )
}

1 Answer 1

22

Setting the state is asynchronous so you would almost always see the old value. Instead, use the callback the function provides:

this.setState({
    loggedIn: val
}, () => console.log(this.state.loggedIn));

This is particularly useful when you need to do something AFTER setting a new state.

6
  • 1
    For more information, checks notes under setState documentation.
    – Yuya
    Jun 21, 2016 at 17:28
  • I didn't know that! Why is setState asynchronous? Not like it has to hit a database. Aren't we talking about milliseconds here? Aug 4, 2016 at 18:44
  • Yeah not sure. Maybe it's due to the way it triggers the rest of the lifecycle methods.
    – ZekeDroid
    Aug 4, 2016 at 20:28
  • can you be more specific?
    – ZekeDroid
    Apr 4, 2018 at 13:17
  • @Lavaraju did you found any solution for this? Nov 14, 2018 at 7:31

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.