DECOUPLING: Start by creating a directory for MST. As a good engineering practice, I tend to decouple the state management from the view to ease refactoring. You can create a JS file in the mst folder.

While the current application still runs with redux, MST is created side by side for refactoring

2. IMPORTING: NPM install mobx-state-tree and import “types” (for defining the model state), “flow” (for async calls) and getSnapshot (finding out the current state)

3. STORE: Start defining the model (state store). In the image below, the “.model” method is used for defining the actual state object while individual property types are declared using “.boolean”, “.frozen” (immutable object), “.array()”, etc. The official documentation contains more details regarding each type.

4. STATE MUTATOR: The “.actions” method trails behind the state model definition. Actions are sort of like redux actions + reducers in a sense that they mutate the store state. Note the “self” argument. It can be used to refer to properties in the model (ie. self.items, self.loading) or actions (ie. self.getResponseLogs, see below).

5. IMMUTABLE: The actions mutate the state by calling “self.retrievalError = err” in the actions example above. Please keep in mind that for “types.frozen” properties, you need to return a new object since it is immutable. You may choose to use the spread operator or Object.assign({}, …, …) method.

6. ASYNC ACTIONS: Using generators, async processes are treated like first-class citizens in MST. Simply use the “flow” decorator to wrap around the function and use the keyword “yield” in front of async calls. You can use it similar to async/await. (Although the implementation underneath is different). The promise resolve will be the value returned from “yield” line (ie the const session and result values from the example above)while the promise reject is delivered to “catch(err)” line. Finally, don’t forget the “*” beside the “function” to declare it as a generator function.

7. SUBSCRIPTION/EXPORTING: In order to use the MST you need to import the module into your React view component. In the image below, the MST module is “activated/subscribed” using the “create” method before exporting. This pattern allows multiple subscriptions to this module. You can import this module from any file and it will simply-work (see the subsequent image).

Activate the MST with CREATE method with initial state as param object

import the “activated” MST module into React view component

Simply use the state properties from the MST module in the view component