Give a custom Hook options, and use it for two counters with different rules.
What to build
Two counters with their own limits, from one Hook.
Requirements
- Write
useCounter({ start, min, max, step })returning{ value, increment, decrement, reset }; the value never leaves the range min to max, and reset goes back to start. Apprenders two sections with the classesguests(start 2, min 1, max 6, step 1) andvolume(start 50, min 0, max 100, step 10). Each has aspanwith the value and the buttons-,+andReset.
Constraints
App must not call useState itself.
Example
Pressing + five times on guests shows 6, the maximum; pressing - six times on volume shows 0.
Why it works
The rules of counting are written once in the Hook, and each call is configured with its own limits and keeps its own value.
Hints
Hint 1
function useCounter({ start = 0, min, max, step = 1 }) returns { value, increment, decrement, reset }.
Hint 2
Clamp with Math.min(max, ...) and Math.max(min, ...).
Solution
Show one correct solution (try it yourself first)
import { useState } from "react";
function useCounter({ start = 0, min = -Infinity, max = Infinity, step = 1 }) {
const [value, setValue] = useState(start);
return {
value,
increment: () => setValue((v) => Math.min(max, v + step)),
decrement: () => setValue((v) => Math.max(min, v - step)),
reset: () => setValue(start),
};
}
function Counter({ className, counter }) {
return (
<section className={className}>
<button onClick={counter.decrement}>-</button>
<span>{counter.value}</span>
<button onClick={counter.increment}>+</button>
<button onClick={counter.reset}>Reset</button>
</section>
);
}
export default function App() {
const guests = useCounter({ start: 2, min: 1, max: 6, step: 1 });
const volume = useCounter({ start: 50, min: 0, max: 100, step: 10 });
return (
<div>
<Counter className="guests" counter={guests} />
<Counter className="volume" counter={volume} />
</div>
);
}