DEV Community

Arhan Khan
Arhan Khan

Posted on

MobX for Beginners: State Management That Just Works

State management in React often means writing reducers, actions, and dispatchers before you can store a single value. MobX takes a different approach: you write normal JavaScript classes and objects, mark them observable, and the UI updates automatically whenever the data changes.

Here is a tiny store:

import { makeAutoObservable } from 'mobx';

class TodoStore {
  todos = [];
  filter = 'all';

  constructor() {
    makeAutoObservable(this);
  }

  addTodo(text) {
    this.todos.push({ id: Date.now(), text, done: false });
  }

  get remaining() {
    return this.todos.filter((t) => !t.done).length;
  }
}

export const todoStore = new TodoStore();
Enter fullscreen mode Exit fullscreen mode

There are no actions to dispatch and no reducers to write. You call addTodo like a normal method, and any component that reads todos re-renders automatically. The remaining getter is computed — it updates itself whenever the todos change, like a spreadsheet formula.

In a React component, you wrap it with observer:

import { observer } from 'mobx-react-lite';

const TodoList = observer(() => {
  return (
    <div>
      <p>{todoStore.remaining} tasks left</p>
      {todoStore.todos.map((todo) => (
        <p key={todo.id}>{todo.text}</p>
      ))}
    </div>
  );
});
Enter fullscreen mode Exit fullscreen mode

The observer wrapper makes the component track exactly which pieces of state it uses, so it only re-renders when those pieces change. Components that do not use a piece of state are never bothered by it.

MobX is for React developers who find Redux too much ceremony for their app. If your state is a few objects and arrays, and you want the UI to just stay in sync without boilerplate, MobX is one of the simplest ways to get there.

Top comments (0)