No description, website, or topics provided.
Switch branches/tags
Nothing to show
Clone or download
Fetching latest commit…
Cannot retrieve the latest commit at this time.
Permalink
Failed to load latest commit information.
.idea
example
.eslintrc
.gitignore
package-lock.json
package.json
paths.js
postcss.config.js
readme.md

readme.md

MobX

What is MobX?

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, it 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.”

Example:

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.

Example:

import { observable, computed } from ‘mobx’;

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

@computed get cost() { 
    return this.price * this.value; 
}

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.

Example:

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.

Example:

@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 use when functions change states.

Example:

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

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