MobX — Reactive State Management
You are an expert in MobX, the simple and scalable state management library based on transparent reactive programming. You help developers build React applications with observable state, automatic tracking of dependencies, computed values, actions for state mutations, and reactions for side effects — providing a natural, class-based or functional approach where the UI automatically updates when state changes without manual subscriptions.
Core Capabilities
Observable Store
import { makeAutoObservable, runInAction, reaction, autorun } from "mobx";
import { observer } from "mobx-react-lite";
class TodoStore {
todos: Todo[] = [];
filter: "all" | "active" | "done" = "all";
isLoading = false;
constructor() {
makeAutoObservable(this); // Auto-detect observables, computeds, actions
}
// Computed (auto-cached, updates when dependencies change)
get filteredTodos() {
switch (this.filter) {
case "active": return this.todos.filter(t => !t.done);
case "done": return this.todos.filter(t => t.done);
default: return this.todos;
}
}
get stats() {
return {
total: this.todos.length,
done: this.todos.filter(t => t.done).length,
remaining: this.todos.filter(t => !t.done).length,
};
}
// Actions (state mutations)
addTodo(text: string) {
this.todos.push({ id: crypto.randomUUID(), text, done: false });
}
toggleTodo(id: string) {
const todo = this.todos.find(t => t.id === id);
if (todo) todo.done = !todo.done; // Direct mutation — MobX tracks it
}
removeTodo(id: string) {
this.todos = this.todos.filter(t => t.id !== id);
}
// Async action
async fetchTodos() {
this.isLoading = true;
try {
const response = await fetch("/api/todos");
const data = await response.json();
runInAction(() => { // Wrap post-await mutations
this.todos = data;
this.isLoading = false;
});
} catch {
runInAction(() => { this.isLoading = false; });
}
}
}
const todoStore = new TodoStore();
// Observer component — auto-tracks which observables are used
const TodoList = observer(() => {
const { filteredTodos, stats, isLoading } = todoStore;
if (isLoading) return <Spinner />;
return (
<div>
<p>{stats.remaining} remaining</p>
<ul>
{filteredTodos.map(t => (
<li key={t.id} => todoStore.toggleTodo(t.id)}
style={{ textDecoration: t.done ? "line-through" : "none" }}>
{t.text}
</li>
))}
</ul>
</div>
);
});
// Reactions (side effects when state changes)
reaction(
() => todoStore.stats.remaining,
(remaining) => { document.title = `${remaining} todos left`; },
);
Installation
npm install mobx mobx-react-lite
Best Practices
- makeAutoObservable — Use in constructor; automatically makes properties observable, getters computed, methods actions
- observer() — Wrap React components with
observer; only re-renders when accessed observables change
- Direct mutations — Mutate state directly in actions (
this.todos.push(...)) — MobX uses Proxy to track changes
- runInAction — Wrap state changes after
await in runInAction(); required for async actions
- Computed values — Use getters for derived data; MobX caches results and recalculates only when dependencies change
- Reaction for side effects — Use
reaction() or autorun() for logging, localStorage sync, API calls on state change
- Small stores — Create multiple domain stores (AuthStore, CartStore, UIStore); inject via React context or import
- Don't destructure — Don't destructure observables outside observer:
const { count } = store breaks tracking; access via store.count
1---2name: mobx3description: You are an expert in MobX, the simple and scalable state management library based on transparent reactive programming. You help developers build React applications with observable state, automatic tracking of dependencies, computed values, actions for state mutations, and reactions for side effects — providing a natural, class-based or functional approach where the UI automatically updates when state changes without manual subscriptions.4license: Apache-2.05---67# MobX — Reactive State Management89You are an expert in MobX, the simple and scalable state management library based on transparent reactive programming. You help developers build React applications with observable state, automatic tracking of dependencies, computed values, actions for state mutations, and reactions for side effects — providing a natural, class-based or functional approach where the UI automatically updates when state changes without manual subscriptions.1011## Core Capabilities1213### Observable Store1415```typescript16import { makeAutoObservable, runInAction, reaction, autorun } from "mobx";17import { observer } from "mobx-react-lite";1819class TodoStore {20 todos: Todo[] = [];21 filter: "all" | "active" | "done" = "all";22 isLoading = false;2324 constructor() {25 makeAutoObservable(this); // Auto-detect observables, computeds, actions26 }2728 // Computed (auto-cached, updates when dependencies change)29 get filteredTodos() {30 switch (this.filter) {31 case "active": return this.todos.filter(t => !t.done);32 case "done": return this.todos.filter(t => t.done);33 default: return this.todos;34 }35 }3637 get stats() {38 return {39 total: this.todos.length,40 done: this.todos.filter(t => t.done).length,41 remaining: this.todos.filter(t => !t.done).length,42 };43 }4445 // Actions (state mutations)46 addTodo(text: string) {47 this.todos.push({ id: crypto.randomUUID(), text, done: false });48 }4950 toggleTodo(id: string) {51 const todo = this.todos.find(t => t.id === id);52 if (todo) todo.done = !todo.done; // Direct mutation — MobX tracks it53 }5455 removeTodo(id: string) {56 this.todos = this.todos.filter(t => t.id !== id);57 }5859 // Async action60 async fetchTodos() {61 this.isLoading = true;62 try {63 const response = await fetch("/api/todos");64 const data = await response.json();65 runInAction(() => { // Wrap post-await mutations66 this.todos = data;67 this.isLoading = false;68 });69 } catch {70 runInAction(() => { this.isLoading = false; });71 }72 }73}7475const todoStore = new TodoStore();7677// Observer component — auto-tracks which observables are used78const TodoList = observer(() => {79 const { filteredTodos, stats, isLoading } = todoStore;8081 if (isLoading) return <Spinner />;8283 return (84 <div>85 <p>{stats.remaining} remaining</p>86 <ul>87 {filteredTodos.map(t => (88 <li key={t.id} onClick={() => todoStore.toggleTodo(t.id)}89 style={{ textDecoration: t.done ? "line-through" : "none" }}>90 {t.text}91 </li>92 ))}93 </ul>94 </div>95 );96});9798// Reactions (side effects when state changes)99reaction(100 () => todoStore.stats.remaining,101 (remaining) => { document.title = `${remaining} todos left`; },102);103```104105## Installation106107```bash108npm install mobx mobx-react-lite109```110111## Best Practices1121131. **makeAutoObservable** — Use in constructor; automatically makes properties observable, getters computed, methods actions1142. **observer()** — Wrap React components with `observer`; only re-renders when accessed observables change1153. **Direct mutations** — Mutate state directly in actions (`this.todos.push(...)`) — MobX uses Proxy to track changes1164. **runInAction** — Wrap state changes after `await` in `runInAction()`; required for async actions1175. **Computed values** — Use getters for derived data; MobX caches results and recalculates only when dependencies change1186. **Reaction for side effects** — Use `reaction()` or `autorun()` for logging, localStorage sync, API calls on state change1197. **Small stores** — Create multiple domain stores (AuthStore, CartStore, UIStore); inject via React context or import1208. **Don't destructure** — Don't destructure observables outside observer: `const { count } = store` breaks tracking; access via `store.count`