State Management with MobX

In our application, we use MobX for state management. MobX is a library that enables reactive state management in a simple and scalable way. It allows components to automatically update when the state changes. This document explains how we structure our stores and utilize them in the application.

Understanding Stores

Stores in MobX are classes that hold and manage the application’s state. Here is a general structure of a store:
import { makeAutoObservable } from 'mobx';

class ExampleStore {
  // Properties
  private _exampleProperty;

  constructor() {
    makeAutoObservable(this);
  }

  // Actions (Setters)
  setExampleProperty = (value) => {
    this._exampleProperty = value;
  };

  // Computed values (Getters)
  get exampleProperty() {
    return this._exampleProperty;
  }

  // Methods
  exampleMethod = async () => {
    // Perform some action
  };

  clear = () => {
    this._exampleProperty = null;
  };
}
  • Properties are the state that you want to manage.
  • Actions (setExampleProperty) are methods used to modify the state.
  • Computed values (get exampleProperty) are getters that return a processed version of the state.
  • Methods (exampleMethod) can be asynchronous and can perform side effects.

Initializing Stores

Stores are usually instantiated in a central file (e.g., App.tsx) and passed through the context to the rest of the application.
const exampleStore = new ExampleStore();

const stores = {
  exampleStore,
};

Using Stores in Components

To use a store in a component, we wrap the component with inject and observer from mobx-react.
import { inject, observer } from 'mobx-react';

interface ExampleComponentProps {
  userStore?: UserStore;
}

const ExampleComponent = ({
  userStore,
}: ExampleComponentProps): JSX.Element => {
  // Use the store as needed
});

export default inject("userStore")(observer(ExampleComponent));
  • inject injects the store into the component’s props.
  • observer makes the component reactive to changes in the store.

Adding a New Store

When adding a new store, follow these steps:
  1. Define the new store class (e.g., NewStore).
  2. Initialize the store in the central file (e.g., App.tsx).
  3. Add the store to the stores object.
  4. Use the store in components using inject and observer.
By following these guidelines, you can effectively manage and utilize state in our application using MobX.