useCounter
useCounter is a custom React hook for managing a numeric counter with optional min/max bounds, supporting increment, decrement, direct set, and reset operations.
Usage
import { useCounter } from "hookify-react";
export default function CounterComponent() {
const { count, increment, decrement, incrementByValue, set, reset } =
useCounter(0, { min: 0, max: 10 });
return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>+1</button>
<button onClick={decrement}>-1</button>
<button onClick={() => incrementByValue(5)}>+5</button>
<button onClick={() => set(7)}>Set to 7</button>
<button onClick={reset}>Reset</button>
</div>
);
}
API Reference
Parameters
| Parameter | Type | Default | Description |
|---|---|---|---|
initialValue | number | 0 | The initial value of the counter. |
options | { min?: number; max?: number } | {} | Optional bounds. Every update is clamped to min/max when provided. |
Return Value
useCounter returns an object with the following properties. All functions are referentially stable.
| Property | Type | Description |
|---|---|---|
count | number | The current value of the counter. |
increment | () => void | Increments the counter by 1. |
incrementByValue | (value: number) => void | Increments the counter by a specified value. |
decrement | () => void | Decrements the counter by 1. |
decrementByValue | (value: number) => void | Decrements the counter by a specified value. |
set | (value: number) => void | Sets the counter directly to the given value. |
reset | () => void | Resets the counter to its initial value. |
Behavior
- When
minand/ormaxare provided, every update (including the initial value,set, andreset) is clamped within those bounds. - All returned functions have a stable identity across renders.
resetrestores the counter to theinitialValueprovided on the first render (clamped to any bounds).