DEV Community

Abhay Singh Kathayat
Abhay Singh Kathayat

Posted on

Mastering MobX: Simplified and Reactive State Management for React

MobX: A Simple and Scalable State Management Solution for React

MobX is a popular state management library for JavaScript applications, especially in React. Unlike Redux, which relies on a centralized store and explicit action dispatching, MobX takes a more reactive approach to managing state. It automatically updates your application’s state and UI by tracking dependencies and re-rendering only the necessary parts of the application when the state changes.

In this guide, we will walk through the key concepts of MobX, how to set it up with React, and how to use it effectively for state management in your React applications.


1. What is MobX?

MobX is a state management library that leverages reactive programming to manage the state of your application. It automatically tracks and updates the parts of your UI that depend on the state, making it a very efficient and intuitive way to manage application data.

Key features of MobX:

  • Automatic Dependency Tracking: MobX automatically tracks which parts of your application depend on which pieces of state.
  • Simple and Intuitive: With MobX, you don’t need to manually dispatch actions or update the state. MobX reacts to state changes automatically.
  • Declarative: MobX uses an observable approach, where you define your state as observable, and your components automatically re-render when the state changes.
  • Optimized for performance: MobX updates only the components that depend on the changed state, resulting in highly optimized performance.

2. Core Concepts of MobX

MobX is built around a few core concepts that work together to manage state:

1. Observable State

Observable state is the core of MobX. When an object is marked as observable, MobX tracks the state of that object and automatically updates components that depend on it.

Example:

import { observable } from 'mobx';

const counter = observable({
  value: 0,
  increment() {
    this.value++;
  },
  decrement() {
    this.value--;
  },
});
Enter fullscreen mode Exit fullscreen mode
  • The observable decorator makes the counter object reactive. Whenever value changes, any React component that uses this state will automatically re-render.

2. Actions

Actions in MobX are functions that modify the state. By convention, actions should be used to update the observable state, as MobX ensures that the state is updated in a controlled and predictable way.

Example:

import { action } from 'mobx';

const counter = observable({
  value: 0,
  increment: action(function () {
    this.value++;
  }),
  decrement: action(function () {
    this.value--;
  }),
});
Enter fullscreen mode Exit fullscreen mode
  • The increment and decrement methods are actions, defined using the action decorator. These methods modify the state.

3. Computed Values

Computed values are derived from observable state. When the observable state changes, computed values are automatically recalculated, ensuring that the state of the application remains consistent.

Example:

import { computed } from 'mobx';

const counter = observable({
  value: 0,
  increment() {
    this.value++;
  },
  decrement() {
    this.value--;
  },
  get doubleValue() {
    return this.value * 2;
  },
});
Enter fullscreen mode Exit fullscreen mode
  • The doubleValue is a computed value derived from the value observable. Whenever value changes, doubleValue will be recalculated.

4. Reactions

Reactions are side effects that run whenever an observable value changes. Reactions are useful for triggering actions based on state changes.

Example:

import { autorun } from 'mobx';

const counter = observable({
  value: 0,
  increment() {
    this.value++;
  },
  decrement() {
    this.value--;
  },
});

autorun(() => {
  console.log(`Counter value is: ${counter.value}`);
});
Enter fullscreen mode Exit fullscreen mode
  • The autorun function is a reaction that automatically runs whenever counter.value changes. It logs the updated counter value to the console.

3. Integrating MobX with React

MobX integrates seamlessly with React to manage your app’s state. In React, MobX works by using the observer higher-order component to track state changes and automatically update the UI when necessary.

Step 1: Install MobX and React-MobX

To use MobX in a React application, you'll need to install mobx and mobx-react:

npm install mobx mobx-react
Enter fullscreen mode Exit fullscreen mode

Step 2: Create an Observable Store

Create a store that holds your application's state. This store will be observable, and components can react to its changes.

Example:

import { observable, action } from 'mobx';

class CounterStore {
  @observable value = 0;

  @action increment() {
    this.value++;
  }

  @action decrement() {
    this.value--;
  }
}

export const counterStore = new CounterStore();
Enter fullscreen mode Exit fullscreen mode
  • The CounterStore class defines the observable state (value) and actions (increment and decrement).

Step 3: Make React Components Observer

To connect your React components to MobX, you need to use the observer higher-order component from mobx-react. This will allow your components to automatically re-render when the observable state changes.

Example:

import React from 'react';
import { observer } from 'mobx-react';
import { counterStore } from './CounterStore';

const Counter = observer(() => {
  return (
    <div>
      <p>Count: {counterStore.value}</p>
      <button onClick={() => counterStore.increment()}>Increment</button>
      <button onClick={() => counterStore.decrement()}>Decrement</button>
    </div>
  );
});

export default Counter;
Enter fullscreen mode Exit fullscreen mode
  • The Counter component is wrapped with observer, which makes it react to changes in counterStore. When counterStore.value changes, React automatically re-renders the component to reflect the new value.

Step 4: Use the Store in Your Application

Now that your store is set up and your components are observer-wrapped, you can use the store in your application:

import React from 'react';
import { render } from 'react-dom';
import { Provider } from 'mobx-react';
import Counter from './Counter';
import { counterStore } from './CounterStore';

const App = () => (
  <Provider counterStore={counterStore}>
    <Counter />
  </Provider>
);

render(<App />, document.getElementById('root'));
Enter fullscreen mode Exit fullscreen mode
  • Provider is used to inject the store into the application. The Counter component can now access the counterStore directly.

4. Advantages of Using MobX

1. Simplicity

MobX makes it easy to manage state, reducing the boilerplate and complexity commonly found in other state management libraries like Redux.

2. Automatic Re-rendering

When the state changes, MobX automatically handles re-rendering of the components that depend on that state.

3. Fine-grained Observability

MobX ensures that only the necessary components are re-rendered when state changes, improving performance.

4. Declarative State Management

With MobX, state is managed declaratively. You just need to define how the state should behave, and MobX handles the rest.


5. Conclusion

MobX is a powerful and efficient state management library that uses reactive programming principles. With its simple setup and automatic state tracking, it makes managing state in React applications much easier. MobX is especially beneficial for applications that require fine-grained control over updates and performance optimization.

If you're building a complex React application and want an easy-to-understand state management solution, MobX is an excellent choice. It's intuitive, powerful, and works seamlessly with React to deliver an optimized development experience.


Top comments (0)