Learn about a fantastic state management library, MobX, and how to use it in your React projects.

State management is an important topic in every application nowadays. When we’re starting to define the bare bones of our application, after we define which framework or library we will use, the next topic to define is state management.

We have to decide: Should we use a state management library? Which one should we use?

We know for a fact that now, in React, we have a lot of solutions for state management. We can use React Hooks, a functionality released in the 16.7 version that allows us to manage and deal with our state data in functional components, which means that we can stop using class components just for state management. Or, we can use the library that’s been the most widely used in the React community for a long time, Redux.

But there’s another library, one not as famous as Redux, that can help us manage our state data, and it might be worth your consideration.

MobX

MobX is a simple, scalable and powerful state management library. Much like React, which uses a virtual DOM to render UI elements in our browsers, reducing the number of DOM mutations, MobX does the same thing but in our application state.

MobX was created using TFRP (transparently applying functional reactive programming). We can understand it as being a reactive library: It makes our application state consistent and bug-free by using a reactive dependency state graph that will be only updated when needed.

A statement that defines MobX very well is:

Anything that can be derived from the application state, should be derived. Automatically.

MobX has some big differences from Redux. For example, in Redux we can only have one single store in which we store all of our state data; in MobX we can have multiple stores for different purposes. Another big difference is that, in Redux, our state is immutable, while in MobX we can mutate our state.

A lot of people like to explain that MobX treats your application state like a spreadsheet, which is true. Another nice thing about MobX is that it’s a framework-agnostic library, which means you can use it in other JS environments as well, or even in other languages—for example, Flutter.

MobX has four principle concepts that we should learn, to understand how it works: observables, computed values, reactions and actions.

Four boxes: Observable, Computed, Reaction, Action. Observable has two sets of arrows: "Updates" to Computed, and "Triggers" to Reaction. Computed has an arrow "Triggers" to Reaction. Reaction has an arrow "Events" to Action. Action has an arrow "Modify" to Observable.

#mobx #react #web-development

The Guide to MobX
1.95 GEEK