This is a high level introduction to MobX in React based on a Lunch and Learn session. The original presentation can be found here on Google Slides.
Michel Weststrate, the creator of MobX, described it best when he said to think of MobX as “data flow library, that enables you to roll your own state management architecture with minimal effort”.
The documentation goes more in depth:
MobX is a battle tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP)
MobX is a library that can help us manage application state in a simple and scalable way. But what exactly does it mean to do that “transparently applying functional reactive programming”?
Under the hood MobX is following an observable pattern which requires subscribing to values and handling update notifications. It makes this whole abstraction layer transparent. All we need to worry about is making a store and a component.
By marking a value as an
observable value and a React component that consumes data as an
observer, the React components will be reacting to value changes.
When values change we perform functional transformations such as map, reduce, filter, and compose.
MobX alone simply provides the core functionality of dealing with make data observable. In order to have React components actually react to our data we need a binding like mobx-react or its aptly named sibling that sounds like the name of a domestic beer mobx-react-lite.
Here is a diagram I created using the information from the documentation.
Make sure that everything that can be derived from the application state, will be derived. Automatically.
The core principals of MobX (derivations and computed values) ensure everything is automatically derived from the application state.
Observerables originate from the Observer Pattern and essentially provide a common pattern for being to subscribe to data streams.
Observables can be any type of value - functions receive changes by subscribing to values.
In this diagram we see
Observable is an object with a few methods that allows
Observers to be notified of changes.
Here are some examples showing that any type of value can be an observable value:
Here is an example of a very simple store defined in MobX:
Here is a simple example of using MobX in React with
In my slides you can see some additional examples and get a bonus introduction to MobX-State-Tree