Skip to main content
Frontend tutorial

4.2. Create store + first spell

So let's build a store outside React, where everything can reach it. A store is a class: fields hold the state, and actions change it. Write it in /Store.ts:

import { makeAutoObservable } from 'mobx';

export class CounterStore {
value = 0;

constructor() {
makeAutoObservable(this);
}

add = (value: number) => {
this.value += value;
console.log(this.value);
};

reset = () => {
this.value = 0;
};
}

export const store = new CounterStore();

To tell MobX that this class is a store, we use the first spell, makeAutoObservable, in the constructor. After that the object isn't a normal object anymore: fields become state, methods become actions and getters become computed values. We write actions as arrow functions, so they keep this wherever we pass them.

Now Counter can use the store instead of useState:

import { store } from './Store';
import './styles.css';

function Counter() {
const { value, add, reset } = store;

return <div className="counter">
<output>{value}</output>
<button onClick={() => add(-100)}>-100</button>
<button onClick={() => add(-1)}>-1</button>
<button onClick={() => reset()}>0</button>
<button onClick={() => add(1)}>+1</button>
<button onClick={() => add(100)}>+100</button>
</div>;
}
Need a hint?
  • Write actions as arrow functions, so add and reset keep their this after destructuring.

Click +1 a few times: nothing changes. Then open Console under the preview: the value went up. MobX changed it, but React doesn't know that it should render again.

Work locally

You need Node.js 24, pnpm and Git (how to set them up). Clone this step’s starting code:

git clone --depth 1 \
--branch lesson-04-02-first-spell-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
04-02-first-spell
cd 04-02-first-spell
pnpm install --frozen-lockfile
pnpm dev

To keep your own commits: git switch -c my-work.

Browse the source on GitHub (opens in a new tab)

Bring your browser edits

Choose Download my files in the ⋯ menu. It saves the lesson’s files as JSON. Stop the local server with Ctrl+C, copy the download into the project folder and run:

node import-draft.mjs ./04-02-first-spell-my-files.json
pnpm dev

The import replaces the project’s exercise files, so commit or back up local edits first.

Loading this step’s code…
Starting the live preview…