In React project, Redux has occupied half of the world in data management. Why Mobx emerged, what it is, what it can bring to us, and what are its advantages and disadvantages compared with Redux? Today, I will share with you a simple knowledge I have learned, hoping to give you a general understanding of Mobx.

directory

  1. What is Mobx
  2. Different ways of thinking about programming
  3. The difference between Store
  4. Store data in different forms
  5. Objects are operated in different ways
  6. Code comparison
  7. The injection of Props is different
  8. Mobx pros and cons

What is Mobx

Mobx is a Transparently Functional Reactive Programming (TFRP) state management library that makes state management simple and scalable: Anything that can be derived from the application state, should be derived. Automatically.

Any data originating from application state should be retrieved automatically. Its principle is shown as follows:

  1. Action: Defines the Action function that changes the state, including how to change the state;

  2. Store: Centrally manages module states and actions.

  3. Derivation: Data derived from the application state without any other impact is called Derivation, and Derivation exists in the following situations:

A. User interface; B. Derived data; There are two main types of derivation:

  1. Computed Values: Computed Values can always be obtained from the current observable state using pure functions;
  2. Reactions: Reactions are the side effects that need to happen automatically when the state changes — in this case, make it read or write;
import {observable, autorun} from 'mobx';

var todoStore = observable({
    /* some observable state */
    todos: []./* a derived value */
    get completedCount() {
        return this.todos.filter(todo= >todo.completed).length; }});/* a function that observes the state */
autorun(function() {
    console.log("Completed %d of %d items",
        todoStore.completedCount,
        todoStore.todos.length
    );
});

/ *.. and some actions that modify the state */
todoStore.todos[0] = {
    title: "Take a walk".completed: false
};
// -> synchronously prints: 'Completed 0 of 1 items'

todoStore.todos[0].completed = true;
// -> synchronously prints: 'Completed 1 of 1 items'

Copy the code

Different ways of thinking about programming

Redux follows more of the philosophy of Functional Programming (FP), while Mobx thinks more in terms of objects.

Redux advocates the compilation of functional code, such as reducer is a pure function, as follows:

    (state, action) => {
  return Object.assign({}, state, { ... })}Copy the code

A pure function that takes an input and then outputs the result without any other effects, including the parameters received; Always output the same result for the same input.

Mobx’s design is more oriented towards OOP and Reactive Programming, usually wrapping state as an observable so that we can use all the capabilities of the observable and get updates automatically when the state object changes.

The difference between store

Store is where apps manage their data. In Redux apps, we always put all shared app data in one big store, whereas Mobx usually divides app state by module and manages it in multiple independent stores.

Store data in different forms

Redux stores data as JavaScript native objects by default, while Mobx uses observables:

  1. Redux needs to manually track all state object changes;
  2. In Mobx, observables can be listened on and automatically triggered when they change;

Objects are operated in different ways

Redux state objects are usually Immutable:

switch (action.type) {
  case REQUEST_POST:
  	return Object.assign({}, state, {
      post: action.payload.post
  	});
  default:
    retur nstate;
}

Copy the code

We can not operate the state object directly, but always return a new state object on the basis of the original state object, so that it is very convenient to return the application of a state; In Mobx, you can update the status object directly with the new value.

Code comparison

In a Redux application, we first need to configure, create a store, use the Redux-Thunk or Redux-Saga middleware to support asynchronous action, and then use the Provider to inject the store into the application:

// src/store.js
import { applyMiddleware, createStore } from "redux";
import createSagaMiddleware from 'redux-saga'
import React from 'react';
import { Provider } from 'react-redux';
import { BrowserRouter } from 'react-router-dom';
import { composeWithDevTools } from 'redux-devtools-extension';
import rootReducer from "./reducers";
import App from './containers/App/';

const sagaMiddleware = createSagaMiddleware()
const middleware = composeWithDevTools(applyMiddleware(sagaMiddleware));

export default createStore(rootReducer, middleware);

// src/index.js... ReactDOM.render(<BrowserRouter>
    <Provider store={store}>
      <App />
    </Provider>
  </BrowserRouter>.document.getElementById('app'));Copy the code

Mobx apps can inject all stores directly into the app:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'mobx-react';
import { BrowserRouter } from 'react-router-dom';
import { useStrict } from 'mobx';
import App from './containers/App/';
import * as stores from './flux/index';

// set strict mode for mobx
// must change store through action
useStrict(true);

render(
  <Provider {. stores} >
    <BrowserRouter>
      <App />
    </BrowserRouter>
  </Provider>.document.getElementById('app'));Copy the code

The injection of Props is different

  • Redux
// src/containers/Company.jsclass CompanyContainer extends Component {
  componentDidMount () {
    this.props.loadData({});
  }
  render () {
    return <Company
      infos={this.props.infos}
      loading={this.props.loading}
    />}}...// function for injecting state into props
const mapStateToProps = (state) = > {
  return {
    infos: state.companyStore.infos,
    loading: state.companyStore.loading
  }
}

const mapDispatchToProps = dispatch= > {
  return bindActionCreators({
      loadData: loadData
  }, dispatch);
}

// injecting both state and actions into props
export default connect(mapStateToProps, { loadData })(CompanyContainer);

Copy the code
  • Mobx
@inject('companyStore')
@observer
class CompanyContainer extends Component {
  componentDidMount () {
    this.props.companyStore.loadData({});
  }
  render () {
    const { infos, loading } = this.props.companyStore;
    return <Company
      infos={infos}
      loading={loading}
    />}}Copy the code

Mobx pros and cons

  • advantages
  1. Low learning cost: Basic Mobx knowledge is very simple, learning official documents and sample code for half an hour to build a new project instance; However, Redux is more complicated with more processes, which need to configure, create store, compile Reducer and action. If asynchronous tasks are involved, additional code needs to be introduced to redux-Thunk or Redux-saga. Mobx process is much simpler and does not need additional asynchronous processing library.

  2. Object-oriented programming: Mobx supports object-oriented programming. We can use @Observable and @Observer to make JavaScript objects responsive. Redux’s best recommendation is to follow functional programming, which Mobx also supports;

  3. Less template code: Compared with various Redux template code, such as actionCreater, Reducer, Saga/Thunk, Mobx does not need to write such template code;

  • disadvantages
  1. Too much freedom: Mobx provides very few conventions and template code, which leads to very free development code writing. If you do not make some conventions, it is easy to cause the team code style to be inconsistent. Therefore, when there are many team members, you do need to add some conventions.

  2. Scalable, maintainable: You might wonder if Mobx will be able to adapt to late-stage projects. Indeed Mobx is more suitable for use in small to medium sized projects, but that doesn’t mean it can’t support a large project, the key lies in a large project usually need to pay special attention to expanding, maintainability, by contrast, standard Redux have more advantages, and Mobx more freedom, need we make some rules to ensure that the project late to expand, maintain ease;

Reference documentation

  1. Redux & Mobx
  2. Mobx

Original address: yolkpie.net/2020/12/30/…