Repozytorium Web Developera

React MobX

Useful links

Recommended MobX learning path for beginners:

  1. Read README.md of Github repo
  2. Not necessary (in Polish) post na blogu o MobX
  3. Not necessary (in Polish) post o połączeniu React i MobX - router
  4. Ten minute introduction to MobX and React
  5. Not necessary article on Medium about core concept of MobX by it author Michel Weststrate
  6. Not necessary presentation by Michel Weststrate "Michel Weststrate: Real World MobX — ReactNext 2016"
  7. Egghead course Manage Complex State in React Apps with MobX
  8. Mobx tutorial at js.org
  9. New things in MobX 4 (early 2018)

MobX practices

Actions @action

If you call async function which uses then syntax in an action, it should not update state of your app because it is done in another function.


@action
loadWeather = city => {
  fetch(
    `https://abnormal-weather-api.herokuapp.com/cities/search?city=${city}`
  )
    .then(response => response.json())
    .then(data => {
      this.weatherData = data; // WRONG! it's modifying state outside of the action
    })
}

You can enforce MobX to throw an error when you modify state outside of an action:


// MobX 4
import { configure } from "mobx"
configure({ enforceActions: true })

// MobX 3
import { useStrict } from "mobx"
useStrict(true)

Source - MobX async actions. This article also describes other ways of updating state, for example by using runInAction.

MobX 4 features

  • Decorators without decorator syntax
  • Dynamic objects
  • Improved support for asynchronous processes
  • Resource management: onBecomeObserved, onBecomeUnobserved

Source: New things in MobX 4 (early 2018)

React & MobX - start a project

MobX with create-react-app

create-react-app doesn't support decorators. MobX can be used without them but development is faster and easier with them. Here you can find instructions how to enable decorators in the package:

If you don't want to use decorators, here you can find an example of an app with using MobX and standard syntax:

React + MobX + Router example

If you want to start development with this stack, I suggest you to start from understanding below boilerplate:

React & MobX

Local state of components with MobX

While using React.setState you have to remember about it asynchronicity. Next state while using setState without callback shouldn't be dependent on previous state. Moreover, you cannot change local state if component isn't mounted.

MobX forms

I haven't read but this can be good article about forms in MobX: