In mobx, when using observable.array() does it make sense to calculate .length in a @computed property, or it is already cached somehow internally?
Generally what kind of properties does it make sense to cache in a @computed? Should I use it for everything? Can it possibly lead to unneeded recalculations?
The length property of an observable array is defined as follows:
Object.defineProperty(ObservableArray.prototype, "length", {
enumerable: false,
configurable: true,
get: function(): number {
return this.$mobx.getArrayLength()
},
set: function(newLength: number) {
this.$mobx.setArrayLength(newLength)
}
})
All this.$mobx.getArrayLength does is the following:
getArrayLength(): number {
this.atom.reportObserved()
return this.values.length
}
The benefit you will get from caching it in a @computed will be slim to none.
It's a good practice to cache computations that you use often. I personally use it for everything from @computed fullName() { return this.firstName + ' ' + this.lastName; }, to e.g. a cached supercluster. It's more a question of taste, unless you are dealing with heavier computations, when it becomes very useful.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With