Stateful Counter in React
Let's make a button click counter:
function App() {
const [count, setCount] = useState(0);
function clickHandler() {
setCount(count + 1);
}
return <div>
<span>{count}</span>
<button onClick={clickHandler}>+</button>
</div>;
}
You can get rid of the handler function by replacing it with an anonymous arrow function:
function App() {
const [count, setCount] = useState(0);
return <div>
<span>{count}</span>
<button onClick={() => setCount(count + 1)}>+</button>
</div>;
}
Let the state store a number. Display this number in a paragraph. Make two buttons. Let the first button increase the age by one, and the second decrease it.