The original link

What is a Mobx

MobX makes state management simple and extensible through transparently Applying Functional Programming – TFRP. His response principle is:

Anything derived from the application state should be acquired automatically.

React with Mobx development personally feels a lot cleaner than Redux. React provides a mechanism to convert application state into and render a tree of renderable components. MobX provides a mechanism to store and update application state for use with React. React and MobX both provide optimal and unique solutions to common application development problems. React provides a mechanism for optimizing UI rendering by using virtual DOM to reduce the number of expensive DOM changes. MobX provides a mechanism to optimize the synchronization of application state with the React component by using reactive virtual dependency state charts that are updated only when really needed and always up to date.

The core concept

Observable State

MobX adds observable functionality to existing data structures such as objects, arrays, and class instances. You can do this easily by using the @Observable decorator (es.next) to annotate your class properties.

import { observable } from "mobx";

class Todo {
  id = Math.random();
  @observable title = "";
  @observable finished = false;
}
Copy the code

Observable objects can be primitives as well as reference values, such as objects or arrays

Computed Values

With MobX, you can define values that are automatically updated when relevant data changes. This is done using the @computed decorator or the getter/setter function called when using a (extend)Observable.

class TodoList {
  @observable todos = [];
  @computed get unfinishedTodoCount() {
    return this.todos.filter((todo) = > !todo.finished).length;
  }
}
Copy the code

MobX ensures that the unfinishedTodoCount is automatically updated when a new TOdo is added or when the FINISHED property of a ToDO changes.

Make up your head or face all these Other Reactions

Reactions are similar to calculated values, but instead of creating a new value, it can have side effects such as printing to the console, network requests, increments updating the React component tree to patch the DOM, and so on. In short, These Reactions bridge the gap between responsive and imperative programming.

Make it easy to create custom Reactions using the Autorun, reaction, and WHEN functions (autorun, Reaction, and When can be found in the official documentation).

autorun(() = > {
  console.log("Tasks left: " + todos.unfinishedTodoCount);
});
Copy the code

The React components

If you use React, you can turn your (statless) component into a reactive component by adding an Observer function/decorator to the component. Observer comes with the Mobx-React package. The Observer converts React components into derivatives of the data they need to render. There is no such thing as intelligent and mindless components when using MobX. All components are rendered in a clever way, and while defining them in a simple, mindless way, MobX ensures that components are always re-rendered as needed.

import React, { Component } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react";

@observer
class TodoListView extends Component {
  render() {
    return (
      <div>
        <ul>
          {this.props.todoList.todos.map((todo) => (
            <TodoView todo={todo} key={todo.id} />
          ))}
        </ul>
        Tasks left: {this.props.todoList.unfinishedTodoCount}
      </div>); }}const TodoView = observer(({ todo }) = > (
  <li>
    <input
      type="checkbox"
      checked={todo.finished}
      onClick={()= >(todo.finished = ! todo.finished)} /> {todo.title}</li>
));

const store = new TodoList();
ReactDOM.render(
  <TodoListView todoList={store} />.document.getElementById("mount"));Copy the code

What does MobX respond to

My personal understanding is that a response is made to any call to application data (attributes of the Observer) via a Mobx function

MobX reacts to any existing observable properties that are read during the execution of the trace function.

  • “Read” is an indirect reference to an object property and can be done with. (for example user.name) or [] (for example user[‘name’]).
  • The “trace function” is the first input function for computed expressions, the Render () method of the Observer component, and when, Reaction, and Autorun.
  • “During” means tracking only observables that are read while the function executes. It is not important whether these values are used directly or indirectly by the tracing function.

In other words, MobX doesn’t react to it:

  • Value obtained from observable, but outside the trace function
  • Observable that reads from the block of code in an asynchronous invocation

The advantage of Mobx

Simple and extensible

MobX is one of the least intrusive state management libraries. This makes MobX’s approach both simple and scalable:

Use classes and real references

There is no need to standardize data with MobX. This makes the library ideal for extremely complex domain models. PS: Mobx manages application data in a class-like manner, which is fast, easy to understand, easy to manipulate, and the ultimate lightweight flavor!

Ensure referential integrity

Because the data doesn’t need to be standardized, MobX automatically tracks the relationship between state and spawn, and you can get referential integrity for free. Render data accessed via tertiary indirection? No problem, MobX keeps track of them and rerenders them as soon as one of the references changes. In return, old bugs no longer exist. As a programmer, you might not be able to remember that some modified data might affect a seemingly unrelated component in a corner, but MobX doesn’t.

Simpler Actions are easier to maintain

Changing state with MobX is very simple. You simply write down your purpose. MobX will take care of the rest.

Efficient fine-grained observability

MobX builds all the derived graphics in the application to find the minimum number of recalculations needed to stay up to date. “Spawn everything” may sound expensive, but MobX minimizes the amount of recalculation required to build virtual spawn diagrams to keep spawn in sync with state. Simply put, MobX builds more fine-grained “listeners” on the data, rather than programmatically controlling it. MobX sees a causal relationship between derivatives, so it can sort derivatives so that they don’t run multiple times or introduce defects

Operational ease

MobX uses native javascript. Since it is not invasive, it can be used with most javascript libraries without requiring a specific Mobx-style library. So you can continue to use your routing, data retrieval and tool libraries, such as React-Router, Director, SuperAgent, LoDash, and so on. For the same reason, you can use it on both the server side and the client side, as well as in isomorphic applications like React-Native. The upshot is that there are usually fewer new concepts to learn when using MobX compared to other state management solutions.

With Mobx, work hours are cut in half and happiness is doubled

It’s super easy and super fast! Great! Don’t miss it!