Categories
Mobx

State Management with MobX 6 — Creating Observable States

Spread the love

MobX is a simple state management solution for JavaScript apps.

In this article, we’ll look at how to use MobX 6 to add state management into our JavaScript apps.

Creating Observable State

We can create one or more observable states by creating a store.

To do this, we write:

import { makeObservable, observable, computed, action, autorun } from "mobx";

class Count {
  count = 0;
  get doubleCount() {
    return this.count * 2;
  }
  constructor(count) {
    makeObservable(this, {
      count: observable,
      doubleCount: computed,
      increment: action
    });
    this.count = count;
  }

  increment() {
    this.count++;
  }
}

const store = new Count(1);

autorun(() => {
  console.log(store.count);
});

store.increment();

We have the Count class that has the count and doubleCount states.

count is an observable state that we can manipulate.

We add this by setting the count property to observable in the makeObservable call.

The doubleCount getter is used to create a computed state, which is a state derived from other observable states.

The increment method is an action as indicated by setting increment to action .

We manipulate observable state values in actions.

In the constructor, we set this.count to count to initialize it.

Next, we create the Count instance, which is the store.

Then we call autorun with a callback to get the store.count value.

The callback will run whenever a state updates.

So when store.increment is called, the callback will run to log the latest value of store.count .

This also works with computed states, so we can write:

import { makeObservable, observable, computed, action, autorun } from "mobx";

class Count {
  count = 0;
  get doubleCount() {
    return this.count * 2;
  }
  constructor(count) {
    makeObservable(this, {
      count: observable,
      doubleCount: computed,
      increment: action
    });
    this.count = count;
  }

  increment() {
    this.count++;
  }
}

const store = new Count(1);

autorun(() => {
  console.log(store.count);
  console.log(store.doubleCount);
});

store.increment();

to watch the value of both states in the autorun callback.

Conclusion

We can create a data store for any client-side JavaScript app with MobX.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *