Search code examples
javascriptmobx

What are the clear differences between autorun and reaction and when to use which?


What is the difference between autorun and reaction? I'm looking for a full explanation that helps to decide when to use which. Is it possible that reaction can even trigger while autorun does not? How they are related to each other?

Are these both the same?

autorun(() => {
  localStorage.setItem("current_order", JSON.stringify(this.currentOrder)) 
})
reaction(
  () => JSON.stringify(this.currentOrder),
  (json) => { 
    localStorage.setItem("current_order", json) 
  }
)

As far as I know, the first parameter of reaction will evaluate and check for changes, so it is desired for computed values, but shouldn't autorun just work fine if this.currentOrder is observable? Will JSON.stringify(this.currentOrder) in reaction run, even when this.currentOrder is observable and has not changed?


Solution

  • autorun runs immediately after it was initialised, reaction runs only after the data expression has changed after initialisation.

    Also, because reaction runs only when data expression changes you can use other observables in the effect function, which would not work for autorun because it subscribes for all observables you use inside of it, which means reaction gives more fine grained control.

    EDIT:

    Adding an example to make it more clear

    Consider this example, you have two observables A and B, and want to do something with B when A changes, but don't want to do anything when B changes. If you just make autorun it will run when any of the observables changes, so it's not what you want. But with reaction it's possible to only react to the changes of A (by only using A in expression function).