Replacing Redux with MobX as state management

September 5, 2016

MobX is a simple yet powerful state management framework. I’ve created a project template on how to use it in React Native. This will allow anyone with an interest of using MobX with React Native a good starting point.

The most interesting point with MobX is the ability to define simple model and have the framework observing for changes. For example, a counter with simple increment and decrement.

class Counter{
  @observable count = 0;
  id = Math.random()

  increase(){
    this.count++;
  }

  decrease(){
    this.count--;
  }
}

Or one could have an array of counters as below and allow to add or remove counters

class CounterArray {
  @observable counterArray = [];

  addCounter(){
    this.counterArray.push(new Counter())
  }

  deleteCounter(i){
    this.counterArray.splice(i, 1)
  }
}

Then one can easily put them all in a single master store that can be accessed by the rest of the application

let store = {
  counter: new Counter(),
  counterArray: new CounterArray()
}

Accessing it from a React.Component

  render () {
    let counter = this.props.store.counter
    return (
      <View style={styles.container}>
        <Text>Counter Value: {counter.count}</Text>
        <Button onPress={counter.increase}>  +</Button>
        <Button onPress={counter.decrease}>  -</Button>
      </View>
    )
  }

Available here, rn-mobx-template

I’ve also build an Reversi game using this template.