MobX can be underwhelming because as it is too easy to get started with. Or it’s simplicity is too overwhelming to get over redux principles for those who understand redux as well. People are generally skeptic about using MobX as they keep comparing it Redux and have a tough time establishing an analogy.

This article will be discussing how MobX can be used like Redux.

Redux leverages command pattern in order to give a sense of decoupled sub-states. Command pattern involves a command(action), executor(action dispatcher) and receiver(s)(reducer). In case you are familiar with Redux, you already have a fair understanding why Redux is based on command pattern. If you don’t know much about Redux, well, this post is not for you.

Multiple Action Subscriptions

A downside of using MobX may be that you don’t get to subscribe multiple stores to a single event. This is because the stores are classes in MobX, and actions are invoked as functions on these store classes.

Solutions

1. Using service wrappers

To cater to such problems, with MobX we generally create a service that in turn invokes relevant actions on more than one store.

2. Dispatching Actions

Yes, you read it right. We can dispatch actions like we do in redux. But, before proceeding with this weird solution, let’s talk about how Redux is a single tree implementation and MobX is not. Store creation is a fairly static event as far as Redux is concerned. With MobX it is wise to keep references to the stores that are created over time and carefully avoid memory leaks at the same time. Assuming we manage to do this, we too can dispatch actions to each store.

The above code simply keeps references to the stores that been created and dispatch actions to them. Hmm, simply iterates over each store call a function action if it finds one in a store.

Downsides of this architecture

Note that the names of the action functions will have to be hardcoded in each relevant store if we are using classes with the @action decorator. However, if we are not using decorators, then we can simply use a variable which holds the name of the action across multiple stores. e.g.

Bringing back immutability

Well, if you are missing immutability and ImmutableJS too much, just introduce yourselves to modifiers in MobX. When declaring an observable, just use observable.ref to kill the MobX magic. This ensures no conversion to observables, it simply creates an observable reference. And now just make the actions pure functions and you’ll feel right at home.

That’s it. I hope this helps to get over your ex!