logo
Orfeas Voutsaridis
profile

Orfeas Voutsaridis

Software Engineer

linkedin
linkedin

Simplifying State Management in React with MobX

State management is an essential aspect of building complex applications in React. While React's built-in state management (using useState and useReducer) is powerful, it can become cumbersome and difficult to maintain as the application grows. This is where external state management libraries like MobX come in.

MobX is a state management library that provides a simple and scalable solution for managing the state of your React applications. It follows the principles of reactive programming and makes it easy to create observable state and track dependencies.

Here's a simplified guide to using MobX for state management in React:

  1. Install MobX: Start by installing MobX and its companion library MobX React using npm or yarn:

    npm install mobx mobx-react
    
  2. Define your state: Identify the data that needs to be managed and create a MobX store. A store is a JavaScript class that holds the state and provides methods to modify it. For example:

    import { observable, action } from 'mobx';
    
    class CounterStore {
      @observable count = 0;
    
      @action increment() {
        this.count++;
      }
    
      @action decrement() {
        this.count--;
      }
    }
    
    const counterStore = new CounterStore();
    export default counterStore;
    

    In this example, we have a CounterStore that holds a count value and provides increment and decrement actions to modify it. The @observable decorator marks the property as observable, and @action decorator marks the methods as actions that modify the state.

  3. Connect your components: To access the state in your React components, you need to use the observer higher-order component (HOC) from MobX React. This HOC automatically re-renders your component whenever the observed state changes. For example:

    import { observer } from 'mobx-react';
    import counterStore from './CounterStore';
    
    const Counter = observer(() => {
      return (
        <div>
          <button onClick={counterStore.increment}>+</button>
          <span>{counterStore.count}</span>
          <button onClick={counterStore.decrement}>-</button>
        </div>
      );
    });
    
    export default Counter;
    

    Here, the Counter component is wrapped with the observer HOC, which makes it observe changes in the counterStore. When the store's state changes, the Counter component will automatically re-render.

  4. Accessing state in other components: To access the state in other components, you can simply import the store and use its properties and methods. MobX will take care of tracking dependencies and triggering updates when necessary.

    import counterStore from './CounterStore';
    
    const OtherComponent = () => {
      return (
        <div>
          <span>{counterStore.count}</span>
        </div>
      );
    };
    
    export default OtherComponent;
    
  5. Reacting to state changes: If you need to perform additional actions or computations based on state changes, MobX provides a mechanism called reactions. Reactions automatically run whenever one of the observed dependencies changes. Here's an example:

    import { reaction } from 'mobx';
    import counterStore from './CounterStore';
    
    reaction(
      () => counterStore.count,
      (count, reaction) => {
        console.log('Count changed:', count);
      }
    );
    

    In this case, whenever the count property in the counterStore changes, the reaction will be triggered, and the provided callback function will execute. This is useful for handling side effects or triggering additional actions.

That's a simplified overview of using MobX for state management in React. MobX offers additional features like computed properties, reactions, and more, which you can explore.