Front-End Insights

A short introduction to MobX

MobXProgrammingReact

Two weeks ago I wrote about one of the best Flux implementations – Redux. Today, it’s time for a short introduction to MobX, a library which is another approach to state management. I will show you what its main concept is. We will also discuss a basic example on how to use it with React.

First, let’s see what it actually is…

The main concept of MobX

As I wrote before, MobX is a library that makes state management extremely simple and scalable. It applies “transparent functional reactive programming” which actually means that:

Anything that can be derived from the application state, should be derived. Automatically.

On the below image you can see the schema of how MobX works:

the flow of the MobX

MobX is actually created to work with React. It provides a mechanism to store and automatically update the application state. React can use this state to render it as a component. They work together perfectly and this is well described on the MobX project page:

React provides mechanisms to optimally render UI by using a virtual DOM that reduces the number of costly DOM mutations. MobX provides mechanisms to optimally synchronize application state with your React components by using a reactive virtual dependency state graph that is only updated when strictly needed and is never stale.

The core of MobX

The MobX library provides just three concepts: observable state, computed values and reactions. The first two can be achieved by using decorators – please take a look at the example below:

import { observable, computed } from 'mobx';

class Store {
  @observable name = 'Bartek';
  @computed get decorated() {
    return `${this.name} is awesome!`;
  }
}

export default Store;

In the above code we can see the class Store. It contains two properties: value and decorated. The first one is just an observable state value. The second one, decorated, is a computed property which depends on the value property. Every time value changes, it is reflected in the decorated value. Just that simple.

As you can see, to declare an observable value we use the @observable decorator and for the computed value we use the @computed decorator. This might be strange if you use it for the first time but actually you will probably get used to it quickly.

What is important here is that MobX controls not only primitive types but also references, arrays, etc. For that reason, computed values can rely, for example, on the property which is part of the object stored in the array. This might be very useful 😉

The third main concept of MobX is reactions. They “produce a side effect” when the observable value changes. This side effect can be used, for example, by React to incrementally update the component’s tree. This can be shown simply in the example of a custom reaction:

autorun(() => {
  console.log("The most awesome is: " + store.name)
})

The MobX’s autorun function provides you the ability to handle reactions (other ones are autorunAsync and when). In the example above we just print to the console every time the store.value changes.

Reactions are great to use with React. Let’s have a look at a short introduction to MobX with React.

Introduction to MobX with React

Making a React component into a “reactive component” is very easy. You have to just use the @observer decorator on your component’s class:

import React from 'react';
import ReactDOM from 'react-dom';
import { observer } from 'mobx-react';

import Store from './stores/store';

@observer
class App extends React.Component {
  render() {
    return (
      <div className="index">
        <span>{this.props.store.decorated}</span>
        <input defaultValue={this.props.store.name} onChange={(event) => this.props.store.name = event.currentTarget.value}
        />
      </div>
    );
  }
}

const store = new Store();
ReactDOM.render(<App store={store} />, document.getElementById('app'));

In the example above you can see the @observer decorator. It simply wraps the React component’s render method in the autorun function. Thanks to this, MobX can keep the component in sync with the state! Every time the observable state changes, the render method is notified about this fact and the view can be re-rendered.

As you can see in the last line, we just pass the store object as the “prop” of the component. Then we can rely on this.props.store as we normally do.

Changing the value is also very simple. In this subject, MobX is not opinionated so you can do it whatever way you like. You can just change the value of the store in the event handler (like it’s done in the example) or you can introduce an additional layer of abstraction like in Flux. It’s up to you.

Summary

This was just a short introduction to MobX. I will try to work with this library and then write something more about it. As you can see the concept is quite clear and simple. I like the fact that everything is done “automagically”. I just wonder how it works when the store grows. Do you have any experience with the MobX library?

The working example shown in this blog post is available on github – fell free to test it on your own.

Related Post

I recommend Nozbe

Simply Get Everything Done

Get your tasks and projects done thanks to Nozbe system and apps for the Mac, Windows, Linux, Android, iPad and iPhone.

If you want to know more about Nozbe and its capabilities, please take a look at my article about this great application.