Mobx action
is doing the batching, similarly to how ReactJS batches multiple changes.
When you use reactjs click
handler react is automatically batching changes that happen inside it, so you will not see component rendering multiple times, however, if you call setColor
from some other event, let's say after loading some data, and have multiple calls to change the observable inside the setColor
that will trigger the observer three times, and the component will be rendered three times.
When you wrap your function with @action
decorator or you use runInAction
function, only the last value will be used (green
in the code below) and the component will be rendered only once.
setColor(){
// this will render three times
this.color='blue'
this.color='red'
this.color='green'
}
vanilla mobx example that reacts only once:
import { runInAction, observable, reaction, toJS } from "mobx";
const test = observable({
name: "sonic",
nick: "speed demon"
});
// console.log will be called only once with the value "name: 3"
reaction(
() => toJS(test),
data => console.log(`name: ${data.name}`)
);
runInAction(() => {
test.name = "1";
test.name = "2";
test.name = "3";
});
view on codesandbox
Also check out the discussion on the github repo: is @action really necessary?