Skip to content

Instantly share code, notes, and snippets.

@cooperka
Last active June 5, 2020 23:13
Show Gist options
  • Save cooperka/a7a1d94f5ef55dccf68c6f8a91da58cc to your computer and use it in GitHub Desktop.
Save cooperka/a7a1d94f5ef55dccf68c6f8a91da58cc to your computer and use it in GitHub Desktop.
Redux vs MobX comparison

Redux

// Action type.
const ADD_TODO = 'ADD_TODO';

// Action creator.
function addTodo(todo) {
  return { type: ADD_TODO, todo };
}

// Reducer state.
initialState = {
  todos: ['Buy coffee'],
};

// Reducer.
function todoReducer(state = initialState, action) {
  switch (action.type) {
    // Handle each possible type of action.
    case ADD_TODO:
      return {
        ...state,
        todos: todos.concat(action.todo),
      },

    default:
      return state;
  }
}

// Create a store from your reducer.
const todoStore = createStore(todoReducer);

// Invoke an action.
todoStore.dispatch(addTodo('Drink coffee'));

// Render a component.
const TodoSummary = (props) => {
  const { todos } = props;
  return (
    <div>{todos.length}</div>
  );
}

// Extract props for your component.
function mapStateToProps(todoStore, props) {
  return {
    todos: todoStore.todos,
  };
}

// Connect your component to the store.
const TodoSummaryConnected = connect(mapStateToProps)(TodoSummary);

// Render your app.
const App = () => (
  <Provider store={todoStore}>
    <TodoSummaryConnected />
  </Provider>
)

MobX

// Model your data and interactions.
class TodoModel {
  @observable
  todos = ['Buy coffee'];

  @action
  addTodo(todo) {
    // Directly update the state.
    todos.push(todo);
  }
}

// Instantiate your model.
const todoStore = new TodoModel();

// Perform an action.
todoStore.addTodo('Drink coffee');

// Connect your component to the store and render a component.
@inject('todoStore')
@observer
const TodoSummary = (props) => {
  const { todoStore: { todos } } = props;
  return (
    <div>{todos.length}</div>
  );
}

// Render your app.
const App = () => (
  <Provider todoStore={todoStore}>
    <TodoSummary />
  </Provider>
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment