Basic Concepts and Implementation of Mobx….

Hi Everyone ,In this article I want to give a brief description about Mobx .The points we are going to discuss in this article are:

  1. What is Mobx ?
  2. Difference between Mobx and Redux ?
  3. Basic Concepts of Mobx.
  4. Implementation .
  5. Conclusion.
  6. What is Mobx ?

Mobx is a testing library used to make the scalable and simple state management with the help of TFRP (transparently applying functional reactive programming). It will help to make the state consistent. It follows the concept that everything that can be derived from the application state, will be derived automatically. The basic question that Mobx tries to answer is how can we give a state consistent and synchronized rendering .

2. Difference between Mobx and Redux ?

So Now let’s discuss what is the difference between Mobx and Redux:

Mobx is testing library to make simple state management with help of TFRP. Whereas Redux is Java script library for managing the application state. Mobx is mainly written in JavaScript,whereas Redux is originally written in ES6. In Mobx, there is more than one store for data storage, whereas In Redux, there is only one large store for data storage. Mobx is mainly used for small and simple applications, whereas Redux is mainly used for complex and large applications. Mobx gives good performance ,whereas Redux is not much efficient. These are some of the theoretical difference now let’s have some technical classification between them. So the first point is storing data, Redux uses a normal javascript object to store the data, on the other hand Mobx uses an observable to store the data, means you can listen to a observable for automatically track changes that occurs to the data, In Redux all the updates have to be tracked manually. The second point is immutable and mutable modification of states, Redux uses immutable states that means the states are read only and you cannot directly over write them,In Redux the previous state is replaced by a new state,As a result,Redux is pure and it uses pure function,In Mobx states can be overwritten we can simple update a state with the new values.As a result Mobx can be termed as impure.

3. Basic Concepts of Mobx:

Basic Concept of Mobx
  1. First of all, there is the application state. Graphs of objects, arrays, primitives, references that forms the model of your application. These values are the “data cells” of your application.
  2. Secondly there are derivations. Basically, any value that can be computed automatically from the state of your application. These derivations, or computed values, can range from simple values, to complex stuff like a visual HTML representation of your application. In spreadsheet terms: these are the formulas and charts of your application.
  3. Reactions are very similar to derivations. The main difference is these functions don’t produce a value. Instead, they run automatically to perform some task. Usually this is I/O related. They make sure that the DOM is updated or that network requests are made automatically at the right time.
  4. Finally there are actions. Actions are all the things that alter the state. MobX will make sure that all changes to the application state caused by your actions are automatically processed by all derivations and reactions. Synchronously and glitch-free.
Overall Flow of Mobx

So we got a brief concept of what is Mobx ,Now we will discuss about some topics which we should know before start coding in Mobx those are:

  1. Observable
  2. Observer
  3. Computed
  4. Action
  5. When
  6. Autorun
  7. Observable:

The observable allows us to turn any data structure or property into an observable state so that other things can keep track of these observable changes and values.@observable are used to decorate our state attribute basically through observable we have been saying Mobx please track their value so that when there value is updated we can update and change the DOM structure.

2. Observer:

The observer are those DOM structure which actually get update whenever the value of the observables changes, so the component which are marked with observer decorator from Mobx ,simply talk Mobx this component renders can be derived from relevant observable ,do it so whenever needed,means observer allows us to keep track of changes in observables so that React gets notified on any change and starts re-rendering. They are provided by the mobx-react package.

3. Computed:

The computed property allows us to derive some value based on the state change. The computed values are obtained by performing some sort of calculations on observables. The basic principle of Mobx is find the smallest amount of state in the class and derive all the derivatives from it . So we mark the derivation with computed, the observable property can be completely drive from other observable ,computed value are very similar to formula in spreadsheet, it is very important to know computed value are not allowed to produce side effect like changing state,instead they should be passing functions in terms of other observable or other computed value.In order to mark computed value ,we have to consume them with reactions, thus observer is the example of reaction,it does not produce a value instead they produce the side effect , the side effect of the observable decorator is that it flashes the render to the DOM. Computed values are side effect free because Mobx decides the best moment to re-evaluate the expressions. This is why instead of having million of computed property still Mobx can actively trace only few of them,mainly those which are directly and indirectly used by Mobx reaction.

4. Action:

The action allows us to change the state i.e. values of observable. The state data should not be modified outside actions to ensure code scalability. Action is the fourth concept of Mobx as it access any piece of codes which tries to alter the code . An action can be implicit or explicit ,if we modify state in console we are calling an action implicitly ,but for security we avoid this approach ,because it may led to accidentally change state in our code .So Mobx provides @ action to explicitly mark your code where our action leaves,Again to restrict the implicit modification of observable states we can use UseStrict method from Mobx ,it will not allow to change the observable values without actions.

5 . When:

When comes in the picture when we want to create our own custom reactions,When takes 2 parameters the 1st parameter is an expression ,which get ultimately re-evaluated until it returns true. and 2nd parameter is a function which is invoked when the 1st one returns true.

6. Autorun:

Autorun is a reaction function it takes only one argument ,one function ,and it keep that function running until it is manually disposed. Autorun is used internally by the observer server.

These are the basic concepts we should know before start coding with Mobx.

4. Implementation:

To have more clarity on what we have discussed in this article so far ,we will developing a simple application which is like a facebook post ,means there is a post having an image we can like the post and can also comment on that post, So let’s start coding. The first thing we will see is the folder structure of our code base:

Folder Structure

So our folder structure is having src folder which is having components ,css and store. Store folder stores the observable data ,css folder contains all the styling applied in our application and components contains the component used in our react application. Index.html is root html file of our application and main.js is the root folder which actually contains all other components,And lastly there is a .babelrc file which is having the default settings to make Mobx working properly in our application:

.babelrc

So these are the pre-settings we have to do to work with Mobx in our application. Now we have to install few npm packages those are @ babel/plugin-proposal-class-properties , @ babel/plugin-proposal-decorators, mobx and mobx-react.To install those npm packages we have to run this command on your treminal:

npm i @babel/plugin-proposal-decorators @babel/plugin-proposal-class-properties mobx mobx-react

So let’s start coding the first file which we are going to see is index.html:

index.html

Our index.html is very simple and self explanatory ,it’s having bootstrap cdn and cdn of font awesome.Now we will see our store where the whole states are present, we create a file name Store.js inside store folder:

Store.js

In Store.js , we have imported observable, action and computed from ‘mobx’ .Our Store class is having observable state likesCount which counts the number of likes to our post ,and comments which is an array having all the comments posted on that post. As we have discussed earlier we use actions to modify the observable states explicitly so we have defined two actions updateCount which is used to update the like count and postComment which is used to push new comment on our comments state whenever new comment is generated, we are also having a computed state named commentsCount which is used to get the current number of comments in our comment array. Lastly we are creating an instance of our class Store(storeInstance) and exporting it .We are going to use this storeInstance in our main.js ,so that this store can be accessed by all other components /child components.So now let’s see the main.js file:

main.js

In main.js we have imported storeInstance from our Store.js files and then we have created a context(StoreContext) and we are wrapping our post component with StoreContext.Provider where value is having our Store class instance .Now let’s see our Post.js file:

Post.js

In Post.js , we have imported Card component ,Form component and Comments component and inside a container div we are rendering them .Card will contain the post which is having like count and comment count. Form is the input form for entering comments .Comments contain the list of all the comments.Now let’s see the components one by one, let’s start with Card.js:

Card.js

In Card.js we have imported Count.js which shows the number of likes and comments on the post whereas Button.js is having the Button to like and comment on post.But here we have imported another store instance named imageStore.let’s first create that store,create a file named ImageStore.js:

ImageStore.js

In ImageStore.js, we have imported action,runInAction and observable from mobx . Let’s create an image store with observable imagrUrl containing default value. Then we create a fetchImage action that returns the JSON response of a single character.After await a new asynchronous function is started, so after each await , state modifying code should be wrapped as action. One way is to use the runInAction, which is a simple utility that takes a code block and executes in an anonymous action. Here we are wrapping the state modifying part after await in runInAction. Lastly we have created an instance of our ImageStore class and export it ,this ImageStore is used in Card.js. Now let’s see the Count.js:

Count.js

In Count.js, we have imported StoreContext from main ,useObserver from mobx-react, and UseContext from react, after that we create a variable store which will be having all the state which are stored inside our StoreContext . so we are rendering the likesCount state and commentsCount state in the DOM. Now let’s see the Button.js:

Buttons.js

In Buttons.js we have imported StoreContext from main.js. it is having two button Like Button and Comment Button .On clicking on Like Button it is trigger updateCount action which will update the likeCount value where as onClicking on Comment button it will trigger a focus event on the div having in ‘comment’.Now let’s see Form.js:

Form.js

In Form.js we have used Consumer method to make the context accessible into the component.Here we have imported StoreContext from main and instead of creating a store, we wrapped the whole component with <StoreContext.Consumer> it will already take a function where store parameter will have all the state which are present in our StoreContext .Thus inside that we create a form onSubmit of it we called handleSubmit function , inside handleSubmit function we are triggering postComment which actually updates our observable state comments inside StoreContext. Let’s see the Comments.js now:

Comments.js

In Comments.js, we imported StoreContext from main.js and useObserver from mobx-react. In this component we create our store and map through the observable state named comments and render the comment inside a table.So the only thing which is remaining in the css part:

main.css
main.css

So our Application is ready ,let’s do npm run start and check in localhost:8080 :

Output

5. Conclusion:

So this is basic implementation of Mobx with React Hooks and Context Api concept.There are many more stuffs we can do using Mobx just go through the documentation it’s really good and also having a series of helpful tutorial.For reference I am leaving the link of the documentation and the whole code base of this article down below:

  1. Mobx Documentation: https://mobx.js.org

2. Code Repo:

So there are many cool stuffs you can do using these awesome libraries, till then don’t stop exploring new things because exploration makes a person better in all aspects of life.

HAPPY CODING…..:)

Web developer by profession,Photographer,Blog Writer,Singer,Pianist,Seeker of Solution