About this App

Lorem ipsum dolor sit amet, consecte tuer adipiscing elit, sed diam tincidunt ut laoreet dolore magna aliq.

Address

302 2nd St
Brooklyn, NY 11215, USA
40.674386 – 73.984783

Folow us on social

What are we using mobx for?

Every React.js application is created with bunch of a components. Every single one has its own state. When state changes (e.g. user has interacted with app) then re-rendering of Virtual DOM tree occurs. MobX is a library that has been created to work perfectly with React.js. It provides simple and scalable states management of a web application, stores and automatically update the application state. React.js can use it to render its components.

MOBX CONCEPTS

MobX has four main concepts:

  • @observable
  • @computed
  • @observer
  • @action

@OBSERVABLE

Observable variables are created with decorator @observable. It defines that application should react when value of a variable is changing. As MobX documentation says: “Observable values can be JS primitives, references, plain objects, class instances, arrays and maps.”

import {observable} from ‘mobx’;
import SomeClass    from ‘./some-class`

@observable testBool = false;
@observable testClass = new SomeClass();
@observable testArray = [‘a’, ‘b’];

@COMPUTED

Computed value depends on state of observable value. It can contain observables and other computed values. Every time when value of content changes it computes its own value again.

import {observable} from ‘mobx’;
import SomeClass    from ‘./some-class`

@observable testBool = false;
@observable testClass = new SomeClass();
@observable testArray = [‘a’, ‘b’];

Computed can be getter (get) or setter (set).

@OBSERVER

Decorator @observer should be used with components that should react on @observable values changes. It wraps the component’s render function.

import {observable} from ‘mobx’;
import {observer} from ‘mobx-react‘;

@observer
class Tester {
    @observable test = true;
}

You should remember that @observer should be the innermost decorator.

@inject(‘example’)
@observer
class Tester {
    @observable test = true;
}

@ACTION

Action changes state, for example it occurs when user interacts with an application. You can make it explicit in your code. Actions should be used when functions change states.

@observable price = 20;
@observable amount = 5;

@action changePrice(newPrice){
    this.price = newPrice;
}

To see our demo of using MobX you can visit our repo:
https://github.com/codetain/mobx-example

Post a Comment