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: >-4 You are an expert in MobX, the simple and scalable state management library5 based on transparent reactive programming. You help developers build React6 applications with observable state, automatic tracking of dependencies,7 computed values, actions for state mutations, and reactions for side effects8 — providing a natural, class-based or functional approach where the UI9 automatically updates when state changes without manual subscriptions.10license: Apache-2.011compatibility: ''12metadata:13 source: https://skillmd.com/skills/eliferjunior/mobx14 author: terminal-skills15 version: 1.0.016 category: Frontend Development17 tags:18 - react19 - state-management20 - observable21 - reactive22 - proxy23 - automatic24---2526# MobX — Reactive State Management2728You 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.2930## Core Capabilities3132### Observable Store3334```typescript35import { makeAutoObservable, runInAction, reaction, autorun } from "mobx";36import { observer } from "mobx-react-lite";3738class TodoStore {39 todos: Todo[] = [];40 filter: "all" | "active" | "done" = "all";41 isLoading = false;4243 constructor() {44 makeAutoObservable(this); // Auto-detect observables, computeds, actions45 }4647 // Computed (auto-cached, updates when dependencies change)48 get filteredTodos() {49 switch (this.filter) {50 case "active": return this.todos.filter(t => !t.done);51 case "done": return this.todos.filter(t => t.done);52 default: return this.todos;53 }54 }5556 get stats() {57 return {58 total: this.todos.length,59 done: this.todos.filter(t => t.done).length,60 remaining: this.todos.filter(t => !t.done).length,61 };62 }6364 // Actions (state mutations)65 addTodo(text: string) {66 this.todos.push({ id: crypto.randomUUID(), text, done: false });67 }6869 toggleTodo(id: string) {70 const todo = this.todos.find(t => t.id === id);71 if (todo) todo.done = !todo.done; // Direct mutation — MobX tracks it72 }7374 removeTodo(id: string) {75 this.todos = this.todos.filter(t => t.id !== id);76 }7778 // Async action79 async fetchTodos() {80 this.isLoading = true;81 try {82 const response = await fetch("/api/todos");83 const data = await response.json();84 runInAction(() => { // Wrap post-await mutations85 this.todos = data;86 this.isLoading = false;87 });88 } catch {89 runInAction(() => { this.isLoading = false; });90 }91 }92}9394const todoStore = new TodoStore();9596// Observer component — auto-tracks which observables are used97const TodoList = observer(() => {98 const { filteredTodos, stats, isLoading } = todoStore;99100 if (isLoading) return <Spinner />;101102 return (103 <div>104 <p>{stats.remaining} remaining</p>105 <ul>106 {filteredTodos.map(t => (107 <li key={t.id} onClick={() => todoStore.toggleTodo(t.id)}108 style={{ textDecoration: t.done ? "line-through" : "none" }}>109 {t.text}110 </li>111 ))}112 </ul>113 </div>114 );115});116117// Reactions (side effects when state changes)118reaction(119 () => todoStore.stats.remaining,120 (remaining) => { document.title = `${remaining} todos left`; },121);122```123124## Installation125126```bash127npm install mobx mobx-react-lite128```129130## Best Practices1311321. **makeAutoObservable** — Use in constructor; automatically makes properties observable, getters computed, methods actions1332. **observer()** — Wrap React components with `observer`; only re-renders when accessed observables change1343. **Direct mutations** — Mutate state directly in actions (`this.todos.push(...)`) — MobX uses Proxy to track changes1354. **runInAction** — Wrap state changes after `await` in `runInAction()`; required for async actions1365. **Computed values** — Use getters for derived data; MobX caches results and recalculates only when dependencies change1376. **Reaction for side effects** — Use `reaction()` or `autorun()` for logging, localStorage sync, API calls on state change1387. **Small stores** — Create multiple domain stores (AuthStore, CartStore, UIStore); inject via React context or import1398. **Don't destructure** — Don't destructure observables outside observer: `const { count } = store` breaks tracking; access via `store.count`