Skip to main content
Frontend tutorial

4.1. Counter with useState

Let's start building our counter. It has a place for the value and buttons that change it: −100, −1, 0, +1 and +100. The layout and the yellow cards of the mobx-example demo are ready, but the buttons don't do anything yet.

We can use useState to store the value for this component:

import { useState } from 'react';
import './styles.css';

function Counter() {
const [value, setValue] = useState(0);

return <div className="counter">
<output>{value}</output>
<button onClick={() => setValue(value - 100)}>-100</button>
<button onClick={() => setValue(value - 1)}>-1</button>
<button onClick={() => setValue(0)}>0</button>
<button onClick={() => setValue(value + 1)}>+1</button>
<button onClick={() => setValue(value + 100)}>+100</button>
</div>;
}
Need a hint?
  • Pass a function to onClick: onClick={() => setValue(0)}, not onClick={setValue(0)}.

Click the buttons. It works, but the value is locked inside Counter, and we want to reach it from everywhere.

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