MobX is a battle-tested library that makes state management simple and scalable by transparently applying functional reactive programming (TFRP).
Defining State & Actions (Modern MobX 6+)
import { makeAutoObservable, observable, action, computed } from 'mobx';
class CartStore {
items = [];
constructor() {
makeAutoObservable(this);
}
get totalCount() {
return this.items.reduce((sum, item) => sum + item.quantity, 0);
}
addItem(product) {
this.items.push(product);
}
removeItem(productId) {
this.items = this.items.filter((item) => item.id !== productId);
}
}
export const cartStore = new CartStore();
Reactions
Reactions run side-effects automatically when observed observables change.
autorun()
Runs immediately, records which observables were accessed, and re-runs whenever any of them change:
import { autorun } from 'mobx';
const disposer = autorun(() => {
console.log(`Cart total count: ${cartStore.totalCount}`);
});
// Stop observing
disposer();
reaction()
Fine-grained reaction that separates data tracking from side-effect execution:
import { reaction } from 'mobx';
reaction(
() => cartStore.items.length,
(length, prevLength) => {
console.log(`Cart item count changed from ${prevLength} to ${length}`);
}
);
when()
Executes a side-effect once when a predicate evaluates to true:
import { when } from 'mobx';
when(
() => cartStore.totalCount > 10,
() => console.log('Eligible for bulk discount!')
);
React Integration (mobx-react-lite)
Wrap components with observer to make them re-render automatically when observable values change:
import React from 'react';
import { observer } from 'mobx-react-lite';
import { cartStore } from './CartStore';
export const CartSummary = observer(() => {
return (
<div>
<h2>Total Items: {cartStore.totalCount}</h2>
<button onClick={() => cartStore.addItem({ id: 1, quantity: 1 })}>
Add Item
</button>
</div>
);
});