Setting Up State Management (MobX) for React Application
MobX uses reactive programming: observable data, computed values, and reactions (autorun, reaction, when). Components wrapped in observer automatically subscribe to exactly those observables they read during render — no more.
MobX wins where state is complex, object-oriented, or when you need to minimize manual work optimizing re-renders.
What's Involved
Designing store classes, setting up decorators or makeObservable/makeAutoObservable, integrating with React via mobx-react-lite, reactions and side effects, DevTools, persistence, store testing.
Installation
npm install mobx mobx-react-lite
Enable decorators in tsconfig.json when using TypeScript:
{
"compilerOptions": {
"experimentalDecorators": true,
"useDefineForClassFields": false
}
}
Store via makeAutoObservable
Most concise — makeAutoObservable. MobX determines what's observable, computed, and action:
import { makeAutoObservable, runInAction } from 'mobx'
class CartStore {
items: CartItem[] = []
loading = false
error: string | null = null
constructor() {
makeAutoObservable(this)
}
get total() {
return this.items.reduce((sum, i) => sum + i.price * i.quantity, 0)
}
get count() {
return this.items.reduce((sum, i) => sum + i.quantity, 0)
}
addItem(product: Product) {
const existing = this.items.find((i) => i.id === product.id)
if (existing) {
existing.quantity++
} else {
this.items.push({ ...product, quantity: 1 })
}
}
async checkout() {
this.loading = true
this.error = null
try {
await api.post('/orders', { items: this.items })
runInAction(() => {
this.items = []
this.loading = false
})
} catch (err) {
runInAction(() => {
this.error = err instanceof Error ? err.message : 'Order error'
this.loading = false
})
}
}
}
export const cartStore = new CartStore()
Timeline
Basic MobX setup — 1–2 hours. Setting up multiple interdependent stores — 2–3 hours. Complex observable graph — 1 day.







