mobx & react

State of things

Maintaining state is one of the big challenges faced by any app. as the app gets bigger, the tasks becomes more complex

setState?

  • each component manages it's own state
  • use callbacks to "lift up" the state to parent component
  • suitable for smaller apps

mobx!

  • allows to store the state in one or more stores
  • unrelated to react but works great with it
  • mobx-react supplies the bridge to make components react (no pun intended) to mobx

Some ES.next

Before we dive in

  • Decorators (higher order functions)

  • Class properties

  • Class fat arrow methods

 

refresher:

  • ES6 getters/setters


@observer
class Counter {
  count = 0;
  
  constructor() {
    super()
  }
  
  handleDec = () => {
    this.count--;
  }
  handleInc = () => {
    this.count++;
  }
}

Installing mobx

yarn add mobx mobx-react

// installing ES.next webpack plugins
yarn add babel-plugin-transform-class-properties --dev
yarn add babel-plugin-transform-decorators-legacy --dev
{
    "presets":["react","es2015"],
    "plugins":["transform-decorators-legacy", "transform-class-properties"]
}

.babelrc

Exercise

Create a ticker using mobx

Mobx - 4 core concepts

  • State

  • Derivations

  • Actions

  • Reactions

Observing and reacting

  • @observable
  • autorun()

Exercise

  1. Create a clock app using setState as normal
  2. Replace setState with mobx

4 core concepts

Chrome Mobx Devtools

  1. renders
  2. obervers - observables
  3. console.log

Higher Order Components

We can use React context mechanism to pass stores to components without passing the store through multiple layers of components: 

  1. Provider
  2. @inject

 

example

Real world using mobX

Made with Slides.com