Give a component its first piece of state.
What to build
A counter with plus, minus and reset buttons.
Requirements
- Show the count in a
pwith the idcount, starting at0. - Buttons
+1,-1andResetchange it; the count never goes below 0.
Constraints
Use useState.
Example
Pressing +1 twice and -1 once shows 1; pressing -1 at 0 keeps 0.
Why it works
The state value survives each render, and every call to its setter makes React show the new number.
Hints
Hint 1
const [count, setCount] = useState(0);
Hint 2
The minus button can use Math.max(0, count - 1).
Solution
Show one correct solution (try it yourself first)
import { useState } from "react";
export default function App() {
const [count, setCount] = useState(0);
return (
<div>
<p id="count">{count}</p>
<button onClick={() => setCount(count + 1)}>+1</button>
<button onClick={() => setCount(Math.max(0, count - 1))}>-1</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}