useCounter is a React hook that manages a numeric counter state with increment, decrement, and reset capabilities. Optionally, you can provide minimum and maximum values to constrain the counter's range.
function useCounter(options?: UseCounterOptions): UseCounterReturn;
type UseCounterOptions = {
initialValue?: number;
min?: number;
max?: number;
step?: number;
};
type UseCounterReturn = {
count: number;
increment: () => void;
decrement: () => void;
reset: () => void;
setCount: (value: number | ((prev: number) => number)) => void;
};import { useCounter } from 'react-simplikit';
function ShoppingCart() {
const { count, increment, decrement, reset } = useCounter({
initialValue: 1,
min: 1,
max: 10,
});
return (
<div>
<span>Quantity: {count}</span>
<button type="button" onClick={decrement}>-</button>
<button type="button" onClick={increment}>+</button>
<button type="button" onClick={reset}>Reset</button>
</div>
);
}The hook automatically ensures that the counter stays within the specified bounds:
- When incrementing beyond
max, the value will stay atmax - When decrementing below
min, the value will stay atmin - When using
setCount, any value outside the bounds will be adjusted to the nearest boundary