Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using @computed for array.length in mobx?

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?

like image 388
hyperknot Avatar asked Jul 25 '26 05:07

hyperknot


1 Answers

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.

like image 122
Tholle Avatar answered Jul 27 '26 19:07

Tholle