Skip to main content
Frontend tutorial

4.3. Second spell: observer

The counter doesn't change, because we need to tell MobX that this component uses our store. We do that with the second spell, observer:

import { observer } from 'mobx-react-lite';
import { store } from './Store';
import './styles.css';

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

return <div className="counter">
{/* ... */}
</div>;
});

observer remembers which state the component read while rendering and renders it again when that state changes. The console.log in add has done its job, so delete it.

And this is all the magic you need to start working with MobX. But it isn't everything.

Need a hint?
  • observer wraps the whole arrow function: const Counter = observer(() => { ... });

Click the buttons. Now it works.

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-03-second-spell-start-v6 \
https://github.com/adam-zielonka/frontend-tutorial.git \
04-03-second-spell
cd 04-03-second-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-03-second-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…