Challenge: Counter and reset
- React course
- Beginner
- Lesson 83/84
- 6 min
Write a counter with increment, decrement and reset that has a lower bound.
Challenge: Counter and reset
This challenge asks you to write a Counter component. Three buttons: Increment, Decrement, Reset. The count state starts at 0.
Increment: setCount(c => c + 1). Decrement: setCount(c => c - 1). Reset: setCount(0).
Add a guard to prevent going below zero: on decrement, use setCount(c => Math.max(0, c - 1)). So count never goes negative.
Practice Write Counter with guard
Complete the skeleton. Write a Counter component. count state starts at 0. Show <p>{ '{ count }' }</p>. Add three buttons: Increment setCount(c => c + 1), Decrement setCount(c => Math.max(0, c - 1)), Reset setCount(0). Export it.
Starter code
import { useState } from "react";
// Write the Counter component hereSample solution
import { useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
return (
<div>
<p>{count}</p>
<button onClick={() => setCount((c) => c + 1)}>Increment</button>
<button onClick={() => setCount((c) => Math.max(0, c - 1))}>Decrement</button>
<button onClick={() => setCount(0)}>Reset</button>
</div>
);
}
export default Counter;Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 Reset
To reset the counter, call ____.
To reset the counter, call setCount(0).
Explanation: Reset with setCount(0).
2 Match the counter buttons
| Term | Meaning |
|---|---|
Increment |
c + 1 |
Decrement |
Math.max(0, c-1) |
Reset |
0 |
guard |
Math.max |