Reactions
Reactions can really change the world for your app. They are the side-effect causing behaviors that react to the changes in observables. Reactions complete the core triad of MobX and act as the observers of the observables. Take a look at this diagram:
MobX gives you three different ways to express your reactions or side-effects. These are autorun()
, reaction()
, and when()
. Let's see each of these in turn.
autorun()
autorun()
is a long-running side-effect that takes in a function (effect-function
) as its argument. The effect-function
function is where you apply all your side-effects. Now, these side-effects may depend on one or more observables. MobX will automatically keep track of any change happening to these dependent observables and re-execute this function to apply the side-effect. It's easier to see this in code, as shown here:
import { observable, action, autorun } from 'mobx';
class Cart {
@observable modified = new Date();
@observable.shallow items = [];
constructor()...