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.