Mobx With React

Learn via video courses
Topics Covered

Overview

MobX is a popular library for managing the state of a React application. It is based on the concept of observables, which allow components to automatically update when the underlying data changes. MobX also includes a powerful system for creating and managing computed values, which are automatically updated based on the state of the application.

Introduction to MobX

MobX react is a state management library for JavaScript applications, including React. It provides a simple and intuitive way to manage the state of a React application, making it easier to write scalable and maintainable code. In this article, we will explore the basics of MobX and its integration with React, including its key concepts and benefits.

One of the main benefits of MobX react is its ability to simplify state management. It eliminates the need for complex props and callbacks by allowing you to store your state in a centralized store and access it directly from any component that needs it. This can greatly reduce the amount of boilerplate code and make your application easier to understand and maintain.

Another key concept in MobX react is the use of observables, which allow components to automatically update when the underlying data changes. Observables can be any JavaScript data type, including arrays and objects, and can be used to manage both simple and complex data structures. When an observable is updated, any component that is observing it is automatically re-rendered with the new data.

In addition to observables, MobX react provides a powerful system for creating and managing computed values. Computed values are automatically updated based on the state of the application and can be used to simplify complex state calculations. This can help to make your code more readable and maintainable, as well as provide a performance boost by reducing the number of unnecessary re-renders.

MobX Core Concepts

MobX is a state management library that provides a simple and intuitive way to manage the state of a JavaScript application. The core concepts of MobX are state, actions, and derivations.

State refers to the data that defines the current state of the application. In MobX, state is stored in a centralized store and can be accessed directly from any component that needs it. The state can be any JavaScript data type, including arrays and objects, and can be used to manage both simple and complex data structures.

Actions are the functions that modify the state in MobX. They represent the changes to the state and can be triggered by user interactions, network requests, or any other event that affects the state of the application. Actions should be written in a way that is predictable and testable, and they should not perform any side effects that affect the state of the application outside of the MobX store.

Derivations are the values that are automatically updated based on the state of the application. There are two types of derivations in MobX: reactions and computed values.

Reactions are functions that are automatically executed whenever one of their inputs (observables) changes. They are used to perform side effects in response to changes in the state, such as updating the UI or sending network requests. Reactions can be triggered by any change to the state, and they are executed as soon as possible after the change occurs.

Computed values are values that are calculated based on the state of the application. They are automatically updated whenever one of their inputs (observables) changes, and they can be used to simplify complex state calculations. Computed values are used to derive values from the state that are used frequently in the application, such as the total number of items in a shopping cart or the average rating of a product.

Using MobX to Create a Store

Using MobX to create a store involves creating an object that represents the state of the application and using MobX to manage the state of that object. In this section, we will go through the steps to create a store in MobX and cover the following points in detail:

Create new items : To create new items in the store, we can define an action that adds the item to the store. The action should be written in a way that is predictable and testable, and it should not perform any side effects that affect the state of the application outside of the MobX store.

Automatically update items : To automatically update items in the store, we can use MobX's observables. Observables are any JavaScript data type, including arrays and objects, and they allow components to automatically update when the underlying data changes. When an observable is updated, any component that is observing it is automatically re-rendered with the new data.

Remove items : To remove items from the store, we can define an action that removes the item from the store. This action should be written in a way that is predictable and testable, and it should not perform any side effects that affect the state of the application outside of the MobX store.

Grant access for get : To grant access for getting items from the store, we can define getters that return the desired data from the store. Getters should be used to derive values from the state that are used frequently in the application, such as the total number of items in a shopping cart or the average rating of a product.

Assign id : To assign an id to each item in the store, we can use a unique identifier such as a UUID. The id can be used to identify items in the store and to keep track of their state.

Final implementation : To represent the final store with all the functions created to add, update and delete.

Initialize storefront : To see the store in action we can initialize the store just as we initialize javascript classes.

Let's now go through the final implementation of a store in MobX. We will create a store for a simple shopping cart application that stores the items in the cart and allows the user to add, remove, and view items.

Here's a step-by-step guide to creating a store front in MobX for a shopping cart application:

  1. Create new items

Explanation : In the above code a function addItem is created which takes the name and price of the item which is to be added to the cart and pushes the item in the items array.

  1. Automatically update items

Explanation : In the above code a function updateItemis created which finds the item by itme id and then updates the item with new item.

  1. Remove items

Explanation : In the above code a function removeItem is created which removes the item from the cart by finding the item with the help of id.

  1. Grant access for get

Explanantion : In the above code a function getItem is created which gives the item from the cart based on the id of the item.

  1. Assign id

Explanantion : In the above code a id is given to each item in the cart when it is added to the cart and the id is updated so that the id is unique for each item added to the cart.

  1. Final Implementation

Explanation : The final implementation of the store contains all the function of add, update, remove and getById which completes the shopping cart store.

  1. Initialize storefront

Explanation : In the above code a new shopping cart is created which adds new item namely "Iphone" and "Tshirt" to the Cart and get the total amount of the item stored in the cart.

Making the MobX Store Reactive

MobX provides a way to make a class or object reactive using the makeObservable method. When an object or class is made reactive, MobX will track changes to its properties and notify any subscribers (such as React components) when those properties change.

To make a class reactive, you first create a class as normal and then use makeObservable to make the class properties observable. Here's an example of a simple shopping cart class that can be made reactive:

In this example, the ShoppingCart class has an items property that is an array of items in the cart. The addItem and removeItem methods are used to add and remove items from the cart.

By using makeObservable and observable, MobX can now track changes to the items array and notify any subscribers of changes. This means that if a React component is subscribed to the ShoppingCart store, it will re-render whenever the items in the cart change.

This is just a simple example, but it demonstrates the basic idea behind using makeObservable to make a class reactive in MobX. By making a class reactive, you can easily track changes to its properties and respond to those changes in your React components.

MobX provides several configuration options that can be used to customize the behavior of observable objects and classes. Here are a few of the most commonly used configuration options:

1. observable : This is the main decorator used to make properties of a class observable. By marking a property as observable, MobX will track changes to that property and notify subscribers (such as React components) of changes.

2. computed : This decorator is used to create computed properties that are derived from other observable properties. Computed properties are updated automatically whenever their dependencies change, and they can be used just like any other property.

3. action : This decorator is used to mark methods as actions. Actions are used to modify the state of an observable object or class, and they are the only way to change observable properties. When an action is called, MobX will automatically batch all updates together and notify subscribers of changes after the action has completed.

4. reaction : This is a higher-level API for creating reactions, which are functions that are automatically re-run whenever an observable property changes. Reactions can be used to perform side-effects in response to changes in the state of an observable object or class.

5. autorun : This is a convenience function that creates a reaction that runs immediately when it is defined and then re-runs whenever any observable properties it depends on change.

By using these configuration options, you can customize the behavior of your MobX stores to meet your specific needs. For example, you can use the computed and reaction decorators to create derived values that are updated automatically whenever their dependencies change, or you can use the action decorator to ensure that changes to the state of your stores are batched together and notified to subscribers in a performant way.

Making the MobX Store Observable

To make a MobX store observable, you need to use MobX's observables and actions. Observables are used to represent state that can change over time, while actions are used to modify that state in a controlled way.

Here's how you can make a simple MobX store observable:

  1. Create a class that represents your store:
  1. Mark the state that can change over time as observable:
  1. Mark the methods that modify the state as actions:

With these changes, the TodoStore is now a fully reactive MobX store. Whenever the state of the store changes (i.e., when a todo is added or removed), MobX will automatically notify any subscribers (such as React components) of the changes.

In this example, the todos property is marked as observable, so MobX will track changes to that property and notify subscribers of changes. The addTodo and removeTodo methods are marked as actions, so MobX will batch changes made within those methods and notify subscribers of changes after the methods have completed.

By using MobX's observables and actions, you can easily create reactive stores that are easy to manage and update.

Registering And Interacting With The Mobx Store

To interact with a MobX store, you need to first create an instance of the store and then register it with the MobX store. You can then use the store's methods and properties in your React components to access and modify the store's state.

Here's how you can register and interact with a Todo store created using MobX:

  1. Create an instance of the TodoStore:
  1. Register the store with MobX:
  1. Pass the store instance to your React components as a prop:
  1. Use the store's methods and properties in your React components:

By using MobX stores in this way, you can easily manage and interact with your application's state in a reactive and efficient manner. Whenever the state of the store changes, MobX will automatically notify any subscribers (such as React components) of the changes, and they will re-render to reflect the updated state.

Managing Frontend With Mobx And React

Managing frontend with MobX and React is a straightforward process that involves creating a new React app, managing components, and modifying components to add details. Here's a step-by-step guide to doing so:

  1. Create a New React App We will start by creating a new React app using the command line tool. Run the following command in your terminal:
  1. Manage Components Next, we will create the necessary components for our Todo application. We will have a Todo component to display each todo item and a TodoList component to display all the todo items.
  1. Modify Components and Add Details In this step, we will add the MobX store to our application and modify the components to interact with the store.

In the code above, we created a MobX store for our Todo application and added the necessary actions to interact with the store. We also added the observer higher-order component to make the components reactive to changes in the store.

Using MobX to Manage Data from a Remote Server

MobX can be used to manage data from a remote server by utilizing its reactive nature. The process involves making API calls to the server, and then updating the store with the data received. Here is a step-by-step guide on how to implement this:

  • Define a store class and create an instance of it. This store class should have properties that reflect the data you want to manage.

  • Create an action in the store class to make API calls and update the store properties with the data received. The action should be an asynchronous function that makes a call to the server using a library such as Axios or Fetch.

  • In your React components, use the observer higher-order component (HOC) from the MobX library to observe changes in the store and trigger a re-render of the component whenever the store changes.

  • Call the action in the React component and pass it the data received from the API call as an argument. This will trigger an update to the store, which will then trigger a re-render of the component.

  • To make sure that the store is up-to-date with the latest data from the server, you can use the autorun function from MobX to continuously make API calls and update the store.

Here is an example of a Todo store class that makes API calls to a remote server:

In this example, the store has an observable property called todos that will store the data received from the API call. The fetchTodos action makes a GET request to the https://jsonplaceholder.typicode.com/todos endpoint and updates the todos property with the data received.

In your React component, you can use the observer HOC and call the fetchTodos action as follows:

In this example, the component makes a call to the fetchTodos action when it is mounted, which updates the store with the latest data from the server. The component is then re-rendered whenever the store changes, which ensures that it is always up-to-date with the latest data.

MobX vs Redux Thunk

MobX and Redux Thunk are both state management libraries commonly used with React, but they have different approaches to managing state and different use cases.

MobX is a library for reactive programming that allows you to model your application's state as a set of observables, actions, and reactions. MobX provides a simpler and more intuitive way to manage state in your React application, as it allows you to directly modify the state and observe changes to it, without having to write explicit action creators or reducers.

On the other hand, Redux Thunk is a middleware library for Redux, a popular state management library. It provides a way to write action creators that can dispatch multiple actions, perform asynchronous operations, and return functions instead of action objects.

In summary, MobX provides a simpler and more intuitive way to manage state in your React application, while Redux Thunk provides a way to write more complex action creators that can perform asynchronous operations. Whether you choose MobX or Redux Thunk depends on the specific needs of your application and your personal preferences.

Conclusion

  • MobX is a state management library for React applications.
  • MobX is based on the core concepts of state, actions, and derivations including reactions and computed values.
  • MobX allows you to create a store and make it observable by using makeObservable and observable decorators.
  • MobX also allows you to manage your frontend with React, including creating a new React app, managing components, and modifying components.
  • You can also use MobX to manage data from a remote server by using an API or fetch requests.
  • The use of MobX helps keep your application's state consistent and makes it easier to manage complex data.