MobX with React

GFE Architecture Offsite 2018

Introduction

What is MobX

MobX is a simple, scalable and battle tested state management library transparently applying functional reactive programming.

The core design principle:

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

With React

React and MobX are a powerful combination

  • React provides mechanisms to optimally render the UI
  • MobX provides the mechanisms to store and optimally synchronize application state that React then uses

Concepts

State

  • the data that drives the application

Actions

  • an action is any piece of code that changes the state

Derivations

  • are anything that can be computed automatically from the state

Derivations

Computed values

  • are values that can be computed from the current state using pure functions
  • are observable themselves

Reactions

  • are side effects that need to happen when the state changes
  • they run automatically to perform some task
  • they do not produce a value

MobX distinguishes two kind of derivations:

Data Flow

Characteristics:

  • all derivations are updated synchronously by default
  • all derivations are updated automatically and atomically when the state changes
  • computed values are updated lazily

A minimal, consistent set of subscriptions can only be achieved if subscriptions are determined at run-time.

MobX supports a uni-directional data flow:

  • actions change the state
  • state changes trigger an update of all affected structures

Reacting to changes

  • the @observer decorator/function
    • triggers a new render when the relevant data changes
    • prevents re-renderings when the props didn't change
  • the Provider component
    • uses React context to pass stores down to child components
  • the @inject decorator/function
    • makes the stores available to the wrapped component

The mobx-react package provides:

Pros

  • using powerful concepts like observables and functional reactive programming
  • is not opinionated about the structure of the store
  • has a low level of boilerplate, giving it a gentle learning curve
  • impossible to end up with inconsistent state
  • no way to over/under subscribe to change events
  • easy to integrate into an existing project
  • easy to test

Cons

  • the concepts it is based on are not yet widely known in the JavaScript community
  • smaller community compared to Redux
  • little experience with MobX inside the team

Links

 

MobX with React

By kenjiru

MobX with React

How MobX integrates with React

  • 370