ReactQuestion 23 of 28
Task: counter from 0 to 20
Answer out loud or in your head first, then compare.
Answer
I apply the limit when updating, and disabled buttons show the user where the bounds are.
JSX
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
return <>
<button disabled={count === 0}
onClick={() => setCount(c => Math.max(0, c - 1))}>−</button>
<output aria-live="polite">{count}</output>
<button disabled={count === 20}
onClick={() => setCount(c => Math.min(20, c + 1))}>+</button>
</>;
}To be precise: the functional update uses the previous value, so it also works when updates are queued. I check both ends and repeated clicks.
How did it go? Be honest — “Not yet” puts the question on your review list.
Practise in code
- Counter from 0 to 20 — guided self-review