Introduction
MobX supports a uni-directional data flow where actions change the state, which in turn updates all affected views.
- All derivations are updated automatically and atomically when the state changes. As a result, it is never possible to observe intermediate values.
- All derivations are updated synchronously by default. This means that, for example, actions can safely inspect a computed value directly after altering the state.
- Computed values are updated lazily. Any computed value that is not actively in use will not be updated until it is needed for a side effect (I/O). If a view is no longer in use it will be garbage collected automatically.
- All computed values should be pure. They are not supposed to change state.
The following illustrates the above concepts and principles:
import {observable, autorun} from 'mobx';
var todoStore = observable({
/* some observable state */
todos: [],
/* a derived value */
get completedCount() {
return this.todos.filter(todo => todo.completed).length;
}
});
/* a function that observes the state */
autorun(function() {
console.log("Completed %d of %d items",
todoStore.completedCount,
todoStore.todos.length
);
});
/* ..and some actions that modify the state */
todoStore.todos[0] = {
title: "Take a walk",
completed: false
};
// -> synchronously prints 'Completed 0 of 1 items'
todoStore.todos[0].completed = true;
// -> synchronously prints 'Completed 1 of 1 items'