Hook for a clamped, stepped counter with set and reset
Quantity pickers, pagination controls, and volume sliders all hold a number that must stay inside a range and move in fixed steps. Implement a React hook, useBoundedCounter, that manages such a number and exposes the actions a UI needs.
function useBoundedCounter(
initialValue?: number, // default 0
options?: { min?: number; max?: number; step?: number }, // defaults: -Infinity, Infinity, 1
): {
count: number;
increment: () => void;
decrement: () => void;
set: (next: number | ((current: number) => number)) => void;
reset: () => void;
atMin: boolean;
atMax: boolean;
}
You can assume min <= max and step > 0.
count is always within [min, max]. Any value that would fall outside is clamped to the nearest bound. This includes initialValue.increment() adds step, and decrement() subtracts step, then clamp.set(next) accepts a number or an updater function that receives the current count. The result is clamped.reset() goes back to the initialValue passed on the first render (clamped to the current bounds).atMin is true when count === min, and atMax is true when count === max. Use them to disable buttons.increment() calls in one click handler add 3 * step.min, max, and step. If new bounds leave the count outside the range, return the clamped count, and start the next action from that clamped count.increment, decrement, set, and reset keep the same identity across renders, so they can be passed to memoized children.const { count, increment, decrement, atMin, atMax } =
useBoundedCounter(1, { min: 1, max: 10 });
// count 1, atMin true
increment(); // 2
increment(); // 3
decrement(); // 2
const volume = useBoundedCounter(95, { min: 0, max: 100, step: 10 });
volume.increment(); // 100 (clamped, not 105), atMax true
volume.set(-40); // 0, atMin true
volume.set((v) => v + 25); // 25
volume.reset(); // 95
useBoundedCounter(500, { max: 99 }); // count starts at 99
ReactDOM.flushSync.Object.assign(window, { useBoundedCounter }); below “Do not edit below this line”. The tests use it to call your hook.