Reading time: about 3 minutes

The purpose of this article is to introduce Mobx and not to compare other state management tools.

Redux opens the door to front-end state management, but for smaller applications where Redux can add complexity, I would use Mobx for state management.

What is Mobx

Mobx is a library that makes state management easier and easier to extend through functional responsive programming.

It follows the simplest principle:

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

(Everything that can be obtained from the application state should be automatically obtained.)

His principle was simple:

  • Actions is the only function that allows changing state and has other side effects
  • State is a set of observable states and should not contain redundant data (such as states that will not be updated)
  • Computed Value is pure functions that return values that can be derived from state
  • Reactions are similar to Computed Value, but it allows for side effects (such as UI state updates)

The core concept

Observable state

Mobx adds observable functionality to several existing data structures in JavaScript itself, or you can use ES6’s new features to add these functionality through decorators.

Observable objects:

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

var person = observable({
    // Observable attributes
    name: "John".age: 42.showAge: false.// The calculated property
    get labelText() {
        return this.showAge ? `The ${this.name} (age: The ${this.age}) ` : this.name;
    },

    // action
    setAge: action(function(age) {
        this.age = age; })});// The autorun function is used torun the reaction after updating the state
autorun((a)= > console.log(person.labelText));

person.name = "Dave";
// Output: 'Dave'

Copy the code

Observable arrays:

import {observable, autorun} from "mobx";

var todos = observable([
    { title: "Spoil tea".completed: true },
    { title: "Make coffee".completed: false}]); autorun((a)= > {
    console.log("Remaining:", todos
        .filter(todo= >! todo.completed) .map(todo= > todo.title)
        .join(",")); }); todos[0].completed = false;
// Output: 'Remaining: Spoil tea, Make coffee'

todos[2] = { title: 'Take a nap'.completed: false };
// Output: 'Remaining: Spoil tea, Make coffee, Take a nap'

todos.shift();
// Remaining: Make coffee, Take a nap
Copy the code

Observable Map:

import {observable} from "mobx";

const map = observable.map();

map.set("a".100);

console.log(map.get("a"))
// Output: 100

map.observe(({name, newValue}) = > console.log(name, "- >", newValue))

map.set("b".100)
// Output: b -> 100
Copy the code

Native values and references:

import {observable} from "mobx";

const cityName = observable("Vienna");

console.log(cityName.get());
/ / output 'Vienna'

cityName.observe(function(change) {
    console.log(change.oldValue, "- >", change.newValue);
});

cityName.set("Amsterdam");
// Output 'Vienna -> Amsterdam'
Copy the code

Actions

An important concept in state management is that state should be updated in one way. In Mobx, there is no need to trigger events, call distribution functions, or the like; the basic distribution of state is Mobx’s responsibility.

But having Mobx take over obviously limits scalability and usability, so Mobx provides Actions for use. Actions should always use Actions only for functions that modify state. It is recommended to use (@)action for any functions that modify observables or have side effects. Actions can also provide useful debugging information when combined with developer tools.

Reactions

Reactions are similar to calculated values, but instead of creating a new value, it can have side effects such as printing to the console, network requests, increments updating the React component tree to patch the DOM, and so on. In short, These Reactions bridge the gap between responsive and imperative programming.

Use Mobx in React

How to use React?

The Observer function/decorator can be used to transform the React component into a responsive component. It wraps the component’s render function in mobx.autorun to ensure that the component can be forced to refresh whenever the data used in any component rendering changes. The Observer is provided by a separate Mox-React package.

import {observer} from "mobx-react";



var timerData = observable({

    secondsPassed: 0

});



setInterval(() => {

    timerData.secondsPassed++;

}, 1000);



@observer class Timer extends React.Component {

    render() {

        return (<span>Seconds passed: { this.props.timerData.secondsPassed } </span> )

    }

};



React.render(<Timer timerData={timerData} />, document.body);

Copy the code

When using Mobx, make sure that the Observer penetrates the deepest component, because state is passed down, and if the atomic component doesn’t join the mobx observation, it probably won’t work.

Develop reading

The official documentation

10 minutes interactive MobX + React tutorial

Interview: State Management is Easy – React Amsterdam 2016 Developer Conference (Slides)