I'm learning MobX, so I am confused about computed
and state and action alone. D they do the same thing?
In MobX, where is the difference between computed and state? As I understand, both return the state value if there are any state changes.
For example, I have a store like this:
class CountNumber {
@observable count = 0;
@action doubleThis() {
this.count *= 2;
}
@computed get Double() {
return this.count * 2;
}
}
There is a count
state, we can access them by store.count
, but we also can access it by a computed value store.Double
when the state gets changed, but the question is, can we do that by using an action like doubleThis()
in some function? So in real code, can we use both?
The state:
<div>{store.count}</div>
Or the computed:
<div>{store.Double}</div>
So why do we really need a computed?
First of all, there is nothing in common between the two and an action, as an action is to mutate a state (called observable, usually by MobX). In your case, @action doubleThis()
assigns a new value to the count
state, and there is no return
.
That has been said, both a computed and a state (observable) can be consumed the same way, {store.count}
and {store.Double}
in your case. The difference is that a computed value is a getter function (with get
in front of it) and returns a calculated value generally based on an observable. Here is what the doc says about it:
Computed values can be used to derive information from other observables. They evaluate lazily, caching their output and only recomputing if one of the underlying observables has changed. If they are not observed by anything, they suspend entirely.
Conceptually, they are very similar to formulas in spreadsheets, and can't be underestimated. They help in reducing the amount of state you have to store and are highly optimized. Use them wherever possible.