Skip to main content
Frontend tutorial

4.4. Global store + action for adding

We also know the users. One counter is not enough for them. To solve this, we create a new store that holds our CounterStores, and export it as store instead. Each counter also gets an id, so React can tell them apart in a list:

let nextId = 1;

export class CounterStore {
id = nextId++;
value = 0;
// ...
}

export class Store {
counters: CounterStore[] = [new CounterStore()];

constructor() {
makeAutoObservable(this);
}

addCounter = () => {
this.counters.push(new CounterStore());
};
}

export const store = new Store();

Now Counter gets its counter as a prop, and App renders all of them:

import { CounterStore, store } from './Store';

type Props = { counter: CounterStore };

const Counter = observer(({ counter }: Props) => {
const { value, add, reset } = counter;
// ...
});

function App() {
return <main className="app">
{store.counters.map(counter => (
<Counter key={counter.id} counter={counter} />
))}
<button onClick={store.addCounter}>+</button>
</main>;
}

export default observer(App);

App now reads state that can change, so it needs the second spell too. We can use it in the export line.

Need a hint?
  • App reads store.counters, so App needs observer too.

Click + a few times. Every counter keeps its own value.

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