Skip to main content

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

ParameterTypeDefaultDescription
initialValuenumber0The 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.

PropertyTypeDescription
countnumberThe current value of the counter.
increment() => voidIncrements the counter by 1.
incrementByValue(value: number) => voidIncrements the counter by a specified value.
decrement() => voidDecrements the counter by 1.
decrementByValue(value: number) => voidDecrements the counter by a specified value.
set(value: number) => voidSets the counter directly to the given value.
reset() => voidResets the counter to its initial value.

Behavior

  • When min and/or max are provided, every update (including the initial value, set, and reset) is clamped within those bounds.
  • All returned functions have a stable identity across renders.
  • reset restores the counter to the initialValue provided on the first render (clamped to any bounds).