Skip to main content

MobX with React: Complete Guide to Reactive State Management

Managing complex UI state in React doesn't always require verbose boilerplate code. MobX provides a simple, scalable, and battle-tested reactive state management solution that automatically tracks state changes and updates only the components that rely on them.

In this guide, you will learn how MobX works under the hood, how to integrate it with modern React function components, and best practices for building responsive UIs with minimal boilerplate.


1. The Core Triad of MobX

MobX follows a transparent, reactive data-flow model built around three key pillars:

  • 1. Observables (State): Data structures (objects, arrays, primitives) wrapped by MobX so changes to them can be tracked automatically.
  • 2. Computeds (Values): Values derived automatically from state. Computed properties are cached and only recalculate when their underlying observables change.
  • 3. Actions (State Modifiers): Methods that mutate the observable state. Actions ensure state updates are atomic and predictable.

2. Creating a MobX Store in Modern JavaScript

Using makeAutoObservable allows you to define stores without worrying about legacy decorator syntax or complex setup:

import { makeAutoObservable } from 'mobx';

class CartStore {
  items = [];

  constructor() {
    // Automatically marks properties as observables, actions, or computeds
    makeAutoObservable(this);
  }

  // Action
  addItem(item) {
    this.items.push(item);
  }

  // Action
  removeItem(id) {
    this.items = this.items.filter(item => item.id !== id);
  }

  // Computed Property (Cached)
  get totalPrice() {
    return this.items.reduce((sum, item) => sum + item.price, 0);
  }

  // Computed Property
  get itemCount() {
    return this.items.length;
  }
}

export const cartStore = new CartStore();

3. Connecting MobX to React Components

To make React components react to MobX store changes, wrap them using the observer Higher-Order Component from mobx-react-lite:

import React from 'react';
import { observer } from 'mobx-react-lite';
import { cartStore } from './cartStore';

const ShoppingCart = observer(() => {
  return (
    <div style={{ padding: '20px', border: '1px solid #e2e8f0', borderRadius: '8px' }}>
      <h2>Shopping Cart ({cartStore.itemCount} items)</h2>
      
      <ul>
        {cartStore.items.map((item) => (
          <li key={item.id}>
            {item.name} - ${item.price}
            <button 
              onClick={() => cartStore.removeItem(item.id)}
              style={{ marginLeft: '10px' }}
            >
              Remove
            </button>
          </li>
        ))}
      </ul>

      <h3>Total: ${cartStore.totalPrice.toFixed(2)}</h3>

      <button 
        onClick={() => cartStore.addItem({ id: Date.now(), name: 'New Item', price: 29.99 })}
      >
        Add Sample Item
      </button>
    </div>
  );
});

export default ShoppingCart;

4. MobX vs Redux Toolkit

Both MobX and Redux are popular state management choices for React apps, but they take drastically different approaches:

Feature MobX Redux Toolkit
Paradigm Object-Oriented & Reactive Functional & Immutable
State Updates Direct mutations (via Actions) Immutable copies (via Reducers)
Boilerplate Minimal Moderate
Re-rendering Fine-grained & Automatic Selector-driven

Conclusion

MobX offers an intuitive, low-boilerplate alternative for state management in React applications. By combining observables, computed values, and actions, developers can build responsive, high-performance UIs without writing endless action creators or reducers.

Happy Coding! 🚀

Comments

Popular posts from this blog

10 Essential React Performance Optimization Techniques for Faster Web Applications

Overview: Introduction Profiling React Applications Rendering and Reconciliation in React Lazy Loading and Code Splitting in React Memoization and Caching in React Performance Optimization with React Hooks Optimal Data Fetching in React CSS and Styling Optimization in React Server-Side Rendering (SSR) vs. Client-Side Rendering (CSR) Performance Testing and Benchmarking Conclusion Introduction: React.js has revolutionized the world of web development, becoming one of the most popular and widely used JavaScript libraries. Its component-based architecture and reactive nature have empowered developers to build dynamic and interactive user interfaces with ease. However, as web applications become more complex, ensuring optimal performance has become a crucial aspect of the development process. In this blog post, we will delve into the realm of React Performance Optimization. We will explore various strategies and techniques to fine-tune the performance of your React applications, e...

Mastering React Icons: Installation, Customization, and Best Practices (2026 Guide)

Icons are a crucial element of modern web design, helping users navigate interfaces quickly and intuitively. In the React ecosystem, the react-icons package is the most popular library for integrating scalable vector icons effortlessly. In this guide, you will learn how to install react-icons , render icons in your components, customize their appearance, and apply best practices for performance. What is React Icons? The react-icons library utilizes ES6 imports that allow you to include only the icons your project actually uses, keeping your bundle size lean. It aggregates popular icon sets into a single package, including: Font Awesome ( fa / fa6 ) Material Design Icons ( md ) Feather Icons ( fi ) Bootstrap Icons ( bs ) Heroicons ( hi / hi2 ) Ant Design Icons ( ai ) Step 1: Installing react-icons Open your terminal in your React project directory and run one of the following commands based on your pac...