Skip to main content

Using MobX to manage application state in a React application

I have been writing applications using React and Redux for quite some time now and thought of trying other state management solutions out there. It's not that I have faced any issues with Redux; however, I wanted to explore other approaches to state management. I recently came across MobX and thought of giving it a try. The library uses the premise of  `Observables` to tie the application state with the view layer (React). It's also an implementation of the Flux pattern wherein it uses multiple stores to save the application state; each store referring to a particular entity. Redux, on the other hand, uses a single store with top-level state variables referring to various entities.

On Redux vs MobX:

Redux uses functional programming approach to update the state:

(state, action) => newState;

It accepts two arguments - current state and an action and returns a new state. In Redux, the state is immutable i.e. to update the view, the state reference in the Redux store itself should be updated. For example, to add a new item to the cart you would:

(state, action) => {
   return [...state.items, action.item];

instead of

return state.items.push(item);

MobX, on the other hand, uses an object-oriented approach to state management. A store in MobX is nothing but an instance of a class which has observable properties:

class Cart {
    @observable itemsInBag = [];
    @observable itemsInWishlist = [];

The decorator `@observable` (defined in `mobx` library) is used to declare a property in the class as an observable. It's initialized to an empty array and any changes to this array will let the observers know. In this case, the observer is our view component in React:

The above React component class has the `@observer` decorator, declaring that view component will get updated with the changes in the props. Notice `this.props.cart` in the component's render function, the observable property declared in the Cart class - itemsInBag is being observed by this React component. Any additions/deletions/updates in the observable property will rerender the observer component.

Here the view component gets an instance of the cart object as a prop from the parent container:

const cart = new Cart()
return (
  <ShoppingCart cart={cart} />

The view component also has `this.props.cart.bagCount` instead of `this.props.cart.itemInBag.length`; this is on purpose. MobX provides decorators that can derive values from the state. In this case, the bagCount property is declared as a `@computed` property:

class Cart {
    @observable itemsInBag = [];
    @observable itemsInWishlist = [];

    @computed get bagCount() {
       return this.itesmsInBag.reduce((count, bagItem) => {
         return count + bagItem.count;
       }, 0);

The computed getter (get bagCount) function returns the number of items in the cart; it's executed every time the observable properties in the class are updated. This is very handy because the computation logic is present in the Cart class instead of it being in the View component. It means consistency in the model layer and the code remains DRY.

On setting up the environment for using ES7 decorators

I generally use `create-react-app` to quickly scaffold out the front-end and then modify it to add other libraries. However, it reported errors when I started to use the decorators (observable, observer and computed). Later I discovered that ES7 decorators are still at the proposal stage and are not part of the language yet and thus it's not supported in `create-react-app`. I had to use `yarn eject` to get all the configuration in my local setup and then add babel plugins to get the decorators working:

yarn add --dev babel-cli babel-preset-env  babel-plugin-transform-decorators-legacy

and then added .babelrc file to the project's root directory:

  "presets": ["env", "react", "stage-1"],
  "plugins": ["transform-decorators-legacy"]

This should not report any errors when you start the app (using yarn start). Also, there's an option to use the function `extendObservable` to create an observable instead of using ES7 decorators:

extendObservable(this, {
  itemsInBag: [],
  get bagCount() {
    return this.itemsInBag.length;

This is very much ES5 syntax; however, I really liked the ES7 decorators' syntax and I hope it gets accepted in the language.


  1. This is my third time requesting a paper to be written. I am very impressed with the materials and the level of writing is amazing. They have really good writers and I think every paper is money well spent. Rankmywriter service for all who needs awesome essay.

  2. Thanks for sharing an informative blog keep rocking bring more details.I like the helpful info you provide in your articles. I’ll bookmark your weblog and check again here regularly. I am quite sure I will learn much new stuff right here! Good luck for the next!
    web designing classes in chennai | web designing training institute in chennai
    web designing and development course in chennai | web designing courses in Chennai
    best institute for web designing in chennai | web designing course with placement in chennai

  3. Struggling with the Writing Task? Seek Assistance Here

    If you need more professional assistance with your paper, the experts at paper24x7 are ready to offer assistance with it. Fill an order form by specifying what needs to be done, and help will be delivered promptly.

  4. Thanks for sharing this wonderful post which is very informative.
    Assignment Help
    Java assignment help

  5. This comment has been removed by the author.

  6. Prime-Resume is a great place where you can have your programmer resume revampled. They have helped me a lot!


  7. تنظيف منازل بالدمام شركة تنظيف
    تنظيف منازل بالاحساء شركة تنظيف منازل بالاحساء
    تنظيف منازل بمكة شركة تنظيف منازل بمكة
    تنظيف منازل بجدة شركة تنظيف منازل بجدة
    تنظيف منازل بالمدينة المنورة شركة تنظيف المنازل بالمدينة المنورة

  8. I have ordered from this site Craftanessay service many times now, I have a part time job as well as studying so I don't have a lot of free time to write all my essays and assignments. When I first heard about this site I was a little worried to use it but I decided to give a try and it was the best thing I did. Got the grades I was expecting and easy to communicate with the staffs too. Very happy!

  9. It is perfect chance to make a couple of game plans for the future and the opportunity has arrived to be sprightly. I've scrutinized this post and if I may I have the option to need to suggest you some interesting things or recommendations. Perhaps you could create next articles insinuating this article. I have to examine more things about it!360DigiTMG pmp certification in malaysia

  10. This is a great post I saw thanks to sharing. I really want to hope that you will continue to share great posts in the future.
    hrdf contribution


  11. This is a great post I saw thanks to sharing. I really want to hope that you will continue to share great posts in the future.

    hrdf claimable

  12. This is truly an practical and pleasant information for all. Thanks for sharing this to us and more power
    business analytics course


Post a Comment

Popular posts from this blog

De-obfuscating javascript code in Chrome Developer Tools

I had blogged about JavaScript debugging with Chrome Developer Tools  some time back, wherein I have explained how these developer tools can help in debugging javascript code. Today Google Chrome 12 was released and my Chrome browser was updated to this version. As with every release, there have been some improvements made on performance, usability etc,. One feature that stood out for me is the ability to De-obfuscate the javascript code. What is Minification? Minification is the process of removing unnecessary characters such as white spaces, comments, new lines from the source code. These otherwise would be added to make the code more readable. Minifying the source code helps in reducing the file size and thereby reducing the time taken to download the file. This is the reason why most of the popular javascript libraries such as jQuery are minified. A minified jQuery file is of 31 KB in size where as an uncompressed one is about 229 KB. Unfortunately, debugging minified javascript f

Adding beforeRender and afterRender functions to a Backbone View

I was working on a Backbone application that updated the DOM when a response was received from the server. In a Backbone View, the initialize method would perform some operations and then call the render method to update the view. This worked fine, however there was scenario where in I wanted to perform some tasks before and after rendering the view. This can be considered as firing an event before and after the function had completed its execution. I found a very simple way to do this with Underscore's wrap method.

A cheat sheet of keyboard shortcuts in ColdFusion Builder

In my last post I have explained about keyboard shortcuts in ColdFusion Builder 2.0. This blog post contains a list of all shortcut keys and I have listed these keyboard shortcuts based on the categories that it falls into. Well, this post was not planned since users can easily get to know the keyboard shortcuts by navigating to the preferences (ColdFusion -> Profiles -> Keys). However, I met Joshua at Scotch on the rocks in Edinburgh and he suggested that it would be nice to have the list of keyboard shortcuts handy. So this post is for those who would like to have the list with them and refer it whenever required. Keyboard shortcuts for inserting text: These are the keyboard shortcuts which are used to insert some text into the editor: Command Keyboard shortcuts on Windows Keyboard shortcuts on Mac Insert anchor tag CTRL + T, L CMD + T, L Insert bold tag CTRL + T, B CMD + T, B Insert br tag CTRL + T, R CMD + T, R Insert cfabort CTRL + T, A CMD + T, A Insert