Search code examples
reactjsstatemobx

React, MobX. The application state is not updated instantly


My store looks like this

count = 0
increment = () => {
this.count = this.count + 1;
}

And my component, that wrapped in observer

<button onClick = {()=>{
increment()
console.log(count, "after")
}}>{count}</button>

I expect that the console.log line will already have the updated value. That is, count will be equal to one. The component itself is updated, that is, the count value is changed. But in the console.log line, the count value will first be 0, you press again, the count in the component is 2, but in console.log it is one


Solution

  • That's just how closures works, it's not related to MobX. I expect that you have something like that in the code:

    const {increment, count} = store
    
    return <button onClick = {()=>{
      increment()
      console.log(count, "after")
      }}>{count}</button>
    

    So on the first render your onClick has count === 0 in the scope, when you press the button increment increments the count, but onClick still has the old value because that's what it had when it rendered first time. And so on.

    You can read more in React docs about it.

    With MobX you can overcome it by not destructuring the store, then you will always have latest values everywhere:

    return <button onClick = {()=>{
      store.increment()
      console.log(store.count, "after")
      }}>{store.count}</button>