Managing Complex States in React with MobX — An Introduction

Ritesh Sharma
codeburst
Published in
6 min readOct 5, 2020

--

MobX is a library for simple and scalable state management in modern frameworks like React.

State management is one of the biggest concerns while building scalable and complex applications, no matter whether you’re creating a web or mobile app. In this scenario, the “state” refers to the data that describes the UI or which is rendered on UI. The main challenge here is to describe the structure of the state and manage the state according to the user actions on UI.

There are multiple state management options in React but a developer needs to decide which one is best for the project. Sometimes one doesn’t need a state management strategy or framework as React may come up with inbuilt state management strategies with hooks and setState APIs.

Life Without State Management Frameworks

Using a state management framework is optional but it is advisable when you’re building something really complex as offers several advantages:

  1. Global State i.e. only one instance of data.
  2. Easy access to data throughout the application.
  3. Standardizes the way to code and will give a uniform flow of data.
  4. Follows the best software engineering practices like loose coupling and high cohesion.
  5. Easy debugging and developer tools support.

MobX — An Introduction

MobX is a highly scalable yet simple library to manage complex states in modern applications. It applies the concept of functional reactive programming for managing states. MobX and React form a great combination as React renders the state into UI by means of re-usable components and MobX provides a uniform and unidirectional flow of data throughout the application. In general, the flow of the application when a state change happens can be laid out as per the diagram below:

State management cycle

The Observables world

MobX is based on the Observable pattern of Reactive programming. Observables, as the name suggests, are the entities that are observed by someone for changes. Often times, observables are known as producers as they provide data to the observers (consumers). So, as of now, we know that there are two basic things in MobX; an observable and an observer. Here is the complete lifecycle of MobX:

Complete MobX cycle

As can be seen, there are four basic things at the heart of MobX: observables, actions, reactions, and side effects.

Observables

Observables are the entities that capture the state of our application and as they are observed by the observers, the observers get notified as soon as the value of observables changes. This seems to be very simple but can be very handy when we build complex and scalable client-state.

The observables can be a scalar value, an array, a map, or an object. This means all the types of data defined in JavaScript can be made observable. Here are some of the examples of observables in MobX.

Defining observables in MobX

Decorators are the annotations in JavaScript introduced in ES6 that are used in modern frameworks and libraries for annotating the variables, methods, and classes. In MobX we use an @observable decorator to declare the observables.

Actions

Actions mutate the state or observable in MobX. Although we can directly change the observable values, actions act as an interface to do so as it gives declarative names to the operations that we perform using actions. The UI triggers the action and the action mutates the state/observable.

Different ways of defining actions in MobX

Actions are usually defined using the @action decorator. We can also give names to actions that help us while debugging the application. There’s another variation in actions called the bounded actions. These actions help us bind the scope to the targeted object (unlike the normal functions that follow the normal binding rules of JavaScript).

Reactions

Reactions (also known as observers) complete the important trio in MobX as they are the ones that react to the change in observable values. The change in observable values is notified to the reactions and the reactions cause side-effects as well. We can use the @observer decorator or the observer HOC (Higher Order Component) to wrap the component, observe, and react to the changes.

An example of the observer

The observer automatically tracks observables used during render. There are a few characters of observer:

  1. The observer enables your components to interact with the state that is not managed by React and updates that in an efficient way.
  2. The @observer implements memo / shouldComponentUpdate automatically so that children are not re-rendered unnecessarily.
  3. The observer based components sideways load data; parent components won't re-render unnecessarily even when child components will.

Side Effects

Side effects are a result of state-change that are triggered by responding to the notifications coming from the state/observable. Side effects are invoked by the side effects handlers. MobX gives us three ways to implement side effects.

  1. autorun()This function is used for long-running side-effects. It expects a function (effect-function) as an argument. The effect-function is executed when the dependent observable value changes. It returns a disposer method that can be used to cancel anytime.
  2. reaction()This function can also be used for long-running side-effects. It expects two functions (tracker-function and effect-function) as arguments. Here, the effect function is executed only when the data returned by the tracker-function is different. It also gives a disposer function.
  3. when()This function is useful for one-off effects. It also takes two functions (predicate-function and effect-function) as arguments. Every time the dependent observable changes, the predicate-function is executed and if it returns the value true , then only the effect function is executed. The when() function automatically disposes of itself once it executes effect-function.
Different types of side-effects handlers

Putting these all together

Now, after getting knowledge of core and important parts of MobX, let’s put all the things together and see what happens when it comes to building apps with State management in MobX.

An application built with MobX and React

In the above example, there’s a Todo application that implements all the concepts that we’ve learned so far.

The Final Words

MobX is a great state management library used by a lot of big websites built with React and they are doing great. Using a state management library/framework is completely optional so smart decisions should be made by the developer. But if you’re building something complex with a lot of components, modules, and a lot of complex component trees then you should definitely use state management libraries/frameworks as they give you a better way to code keeping best software engineering practices in mind.

I would like to congratulate you that you made it to the end of the article, thanks a lot for reading. Special thanks to Pavan Podila sir for his awesome book on MobX.

You can find the code written in this article on GitHub in this link.

See you until next time, thanks again 🙏.

--

--

Full-stack developer | Flutter | Node.js | Angular | React | Data science enthusiast | Mentor.