State management in React-Native

Redux vs Mobx

Me?

Paolo Mosca

tw: @paolomoscaBCN

Startup Advisor

Business & Tech

Passionate in Mobile

Inline Skater

bla bla bla

YOU?

Some questions

  • Who's using react-native? Professionally?
  • Who knows what state management is?
  • Who knows something about redux / mobx?

The Problem

Applications aggregate Components

Components have internal state accessible with this.state and setState(...)

Inside a component everything works fine

Connection between components can be complex

Sharing or mutating state between components

Uneeded re-render

Let's start the war

Make Love NOT War

Redux

  • single-store
  • immutable state
  • funcional programming
  • normalized state
  • very strict architecture
  • passive (event oriented)

MobX

 

  • multi-store
  • mutable state
  • object oriented
  • object state
  • do what you want
  • reactive (observable)

Redux

  • more boilerplate
  • exponencial learning curve
  • follow the rules
  • easily testable
  • strong community
  • tools

MobX

 

  • linear learning curve
  • lazy rules
  • reactive (observable)
  • magic
  • community & tools

Comparison (pros and cons are relatives)

Best choice?

Redux over Mobx

  • complex projects
  • big teams
  • very structured architectures

Mobx over Redux

  • fast prototyping
  • small teams
  • good internal organization
     

You can always refactor from MobX to redux if needed 

My personal advice

(why MobX?)

Start with Mobx

  • object programming
  • reactive
  • less boilerplate

Go strict

  • when your project / team is growing, force strict using @action @computed instead of direct mutation

React-Native

An app is a small project for definition.

If is not, maybe you're over-engineering.

Code Example - Redux way

const initialState = {
  users: [
    {
      name: 'Paolo'
    },
    {
      name: 'Dan'
    }
  ]
};

// reducer
function users(state = initialState, action) {
  switch (action.type) {
  case 'USER_ADD':
    return { ...state, users: [ ...state.users, action.user ] };
  default:
    return state;
  }
}

// action
{ type: 'USER_ADD', user: user };

// somewhere in the app ...

dispatch({ type: 'USER_ADD', user: user });

Code Example - MobX way

class UserStore {
  @observable users = [
    {
      name: 'Paolo'
    },
    {
      name: 'Dan'
    }
  ];

  // if you want to go strict using @action  

  @action addUser = (user) => {
    this.users.push(user);
  }
}

//somewhere in the app 
userStore.users.push(user); 

// strict case
userStore.addUser(user);

Let's make our hands dirty

  • Connecting to a "real" rest API
  • Listing CoffeeShops
  • Adding Likes

Thanks

 

resources related:

Redux or MobX: An attempt to dissolve the Confusion

http://bit.ly/2q88UkR
contact me: info@paomosca.com

MobX - Redux

By Paolo Mosca

MobX - Redux

Short comparative for state management in React-Native

  • 403