useCounter
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.
Interface
function useCounter(
initialValue: number = 0,
options: UseCounterOptions
): UseCounterReturn;
Parameters
- initialValuenumber
Initial value for the counter. Defaults to 0.
- optionsrequired · UseCounterOptions
The options for the counter.
- options.minnumber
Minimum value the counter can reach. If not provided, there is no lower limit.
- options.maxnumber
Maximum value the counter can reach. If not provided, there is no upper limit.
- options.stepnumber · 1
Value to increment or decrement by. Defaults to 1.
- options.minnumber
Return Value
- UseCounterReturn
object with count value and control functions.
- countnumber
The current count value.
- increment() => void
A function to increment the count.
- decrement() => void
A function to decrement the count.
- reset() => void
A function to reset the count to the initial value.
- setCount(value: number | ((prev: number) => number)) => void
A function to set the count to a specific value or a function that returns a new value.
- countnumber
Example
import { useCounter } from 'react-simplikit';
function ShoppingCart() {
const { count, increment, decrement, reset } = useCounter(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>
);
}