DEV Community

loading...

Exploring the new MobX API

Ryan Dsouza
A Web Dev and Guitarist who loves JS & TS :) Always exploring new technologies and solution patterns. Have a soft spot for DevOps.
ใƒป2 min read

I have always been an avid admirer of MobX and its simple API. Do read my previous posts regarding those in my profile.

Recently Michel Weststrate tweeted about a new API for MobX without the need of decorators or the decorate API.

I have expanded on this example to show the simple API introduced by MobX named makeAutoObservable.

This API removes the need of using decorators which are still experimental and their API might change. This also removes the need of using the decorate method as we used to do before.

export class User {
  name = 'anonymous'

  updateName(name: string) {
    this.name = name
  }
}

decorate(User, {
  name: observable,
  updateName: action
})

Most of you folks would be familiar with the above syntax that we used to use MobX without decorators. One issue that I had with the above was I could easily miss any propery and that wouldn't be obsevable which could lead to unwanted behaviour.

makeAutoObservable solves the above problem and all the class properties are observable by default. The getters are computed and the methods are actions as well.

There's also another method makeObservable that lets us specify the properties that are required to be made as observable if we do not want all properties of the class to be observable by default.

I personally like this API as given the uncertain future of decorators and the pitfalls that I faced with the decorate API, this is a great addition to the library for cleaner code and not needing decorators as a primary API in MobX.

I have created a sandbox with React that you can explore. In this I have shown how we can combine multiple stores with a Root store, create our RootStore context, and fetch those values we require via the useContext hook.

As usual, the best part about MobX being components re-render only when changes are made to the values they're using and not otherwise.

Do let me know your thoughts on this and thanks for reading :)

Discussion (0)