Skip to main content
Frontend tutorial

4. MobX in React

React for me is functions that render the user interface, and MobX is classes that hold the state of the application. In this chapter I'll show you how easy and powerful that connection is.

We'll build counters: a value and five buttons that change it. Then more counters, a limit, a sum and a field where you type the value. You need only two spells for that. The two Bonus lessons at the end keep the counters in the URL and in localStorage.

The finished app is mobx-example (demo). Its code is a little older than these lessons (deleteCounter, addOne), so use it as a reference, not as a starting point. In your own Vite project, MobX is one command away:

pnpm add mobx mobx-react-lite

Lessons​

  1. Counter with useState
  2. Create store + first spell
  3. Second spell: observer
  4. Global store + action for adding
  5. Limit number of counters
  6. Action for deleting
  7. Sum of all counters
  8. Value to input
  9. Reaction (Bonus)
  10. Autorun (Bonus)

04 / MobX in React

Two spells connect a store to React

Two spells connect a store to ReactThe first spell, makeAutoObservable, turns a plain Store class into observable state with actions and a computed sum. The second spell, observer, lets a React component re-render when the values it reads change. A click calls a counter’s add action, the store changes, and the component shows the new total of ten.class Storecounters = [...]addCounter()get sum()first spellmakeAutoObservableobservable235sum = 10second spellobserverobserver(App)10new sumclick +1counter.add(1)derive it, don't duplicate it

First spell: makeAutoObservable. Second spell: observer.