ReactJS Global State Management Using MobX

Introduction


In this article, we will learn about how to handle global state management using the MobX state management library.

I am explaining the need for state management using the below scenario. 
 

What is State in React JS?

 
The state is information/object/ data which can be stored in a central place or individual component. If your application grows and the data flow between various component is high then to manage the data flow & reduce the complexity of data passing process, we have to implement state management.
 
Consider you have parent component and passing props to child component B, then that props is passing to Child component B.  Consider the case if you want to apply theme color of all the child components, you must pass as props. This is called Prop Drilling. As the application grows, it becomes impartial.
 
We can't use props drilling always, you can use State Management and store your theme in a central state and access the state value from all the components directly.
 
There are different kinds of state management libraries available, but here we are going to learn about MobX.
 
MobX is a simple state management library. When compared to Redux, it has less code to implement state management.
 
As I mentioned earlier, a MobX store is just a class that holds the state of your application which can be retrieved through observables. Using actions, we can update the states.
 
MOB X Core Concepts
ReactJS Global State Management Using Mobx
HOW IT WORKS
ReactJS Global State Management Using Mobx
@Observable
 
Mobx listens through observables to identify when the values is changed. It can array objects and with @Observable key words we can decorate the object.
 
@Action
 
Action is a method or function that is used to modify the state of a data. We can decorate with @Action keycard to declare as it is a Mob X Action method.
 
@Inject
 
To use any store value we have to inject the store using @inject.
 
@Observer
 
Any component that needs to update with state will need to be decorated with @observer.
 
Project setup
 
Create a new project using the below command:
 
npx create-react-app reactmobx
 
To install mobx and its dependencies install the below npm packages 
  • npm install mobx –save
  • npm install mobx-react –save
I have used routing to redirect the page hence please install react router dom.
 
Npm install react-router-dom – save
 
For designing the page I am using semantic UI which is similar to bootstrap and has a more interactive css style.
 
To install semantic UI please use the below command,
 
Npm install semantic-ui-react -- save 
Npm install semantic-ui-css – save
 
In index.js please import the css file related to semantic UI to apply the CSS style for the entire application
 
import 'semantic-ui-css/semantic.min.css'
 
Create individual Store Class
 
As per the standard process, we will create an individual store class for each functionality. Here I am going to use only the Login page to maintain the state. Hence, I am creating Auth Store.
 
Create folder Store .Inside that create auth.store.jsx files.
 
auth.store.jsx
  1. import { observable, action, makeObservable } from "mobx";    
  2. class AuthStore {    
  3. @observable isLoggedIn = false;    
  4. @observable loggedinUser = '';    
  5. constructor() {    
  6.    make Observable(this);    
  7. }    
  8. @action.bound setLoggedInStatus = (changeflag) => {    
  9.    this.isLoggedIn = changeflag;    
  10. }    
  11. @action.bound setLoggedInUser = (username) => {    
  12.    this.loggedinUser = username;    
  13.    }    
  14. }    
  15. export default AuthStore;     
@action.bound setLoggedInUser - function to capature username from login page and store into state
 
@action.bound setLoggedInStatus - function to capture the status of whether the user is logged in or not
 
Then create store.jsx file in same-store folder.
stores.jsx
  1. import AuthStorefrom'./auth.store'  
  2. const stores = {  
  3.    authStore:newAuthStore()  
  4. }; export default stores;  
Here we are collecting all the store classes and consolidating them in a single state object.
 
From here all the store classes have been accessed and data has been updated and retrieved.
 
App.Js
 
Here we are passing the store object as a provider .
  1. import { Provider } from"mobx-react";  
  2. importstoresfrom'./store/stores'  
  3. import { BrowserRouter } from'react-router-dom';  
  4. importRoutesfrom"./Routes";  
  5. functionApp() {  
  6. return (  
  7.    <Provider{...stores}>  
  8.       <divclassName="App">  
  9.          <BrowserRouter>  
  10.          <Routes/>  
  11.          </BrowserRouter>  
  12.       </div>  
  13.    </Provider>  
  14. );  
  15. }  
  16. exportdefaultApp;  
Kindly refer to my attached code and create login.jsx and home jsx & Route.jsx
 

Issues facing while setup Mob x

 
Issue 1
 
Experimental support for decorators is a feature that is subject to change in a future release. Set the 'experimentalDecorators' option `to remove this warning.
 
Resolution
 
In VSCode go to preferences -> settings, you will see an option to enable/disable experimentalDecorators. Check it mark it for two things .and save the settings file. Done
 

Issue 2 auth.store.jsx - Support for the experimental syntax 'decorators-legacy' isn't currenntly enabled (4:5)

 
Resolution
 
(Please refer to the code for where to place the created file )
 
npm i --save-dev customize-cra react-app-rewired
 
Add config-overrides.js with,
  1. const { addDecoratorsLegacy, override } = require('customize-cra')  
  2. module.exports = override(addDecoratorsLegacy())  
Add babel.config.js with,
  1. module.exports = {  
  2.    plugins: [['@babel/plugin-proposal-decorators', { legacy: true }]],  
  3. }  
Open package.json / scripts section and search-replace react-scripts -> react-app-rewired.
  1. "scripts": {  
  2.     "start""react-app-rewired start",  
  3.     "build""react-app-rewired build",  
  4.     "test""react-app-rewired test",  
  5. }  
After this, both start, build, and test commands will work with the codebase.
 

Issue 3 : `this.props.history.push` - history not defined

 
Resolution
 
We have created a router and put code inside browser outer in app.js.
 
Expected output
 
Here I have created a login page and once the user has provided the user name then click the login button, the user name is captured in-store. Once the page is redirected to the home page component, there I am reading the user name from the store and displaying it.
 
Output
 
ReactJS Global State Management Using Mobx 
ReactJS Global State Management Using Mobx

Summary

 
In this article, we have learned about creating react state management application using mob-x . Kindly refer to the attached code for reference.