Skip to content

useCounter

Number state with increment, decrement, set, and reset actions.

Number state with increment, decrement, set, and reset actions.

Import

import { useCounter } from '@kamod-ch/hooks'

Live demo

Basic demo

Number state with increment, decrement, set, and reset actions.

Count: 2

import { useCounter } from '@kamod-ch/hooks'

export default function UseCounterDemo() {
  const [count, actions] = useCounter(2, { min: 0, max: 10 })

  return (
    <div>
      <p><strong>Count:</strong> {count}</p>
      <div class="demo-actions">
        <button type="button" onClick={() => actions.dec()}>-1</button>
        <button type="button" onClick={() => actions.inc()}>+1</button>
        <button type="button" onClick={() => actions.set(8)}>Set 8</button>
        <button type="button" onClick={actions.reset}>Reset</button>
      </div>
    </div>
  )
}

API

TypeScript signature
export interface Options {
    min?: number;
    max?: number;
}
export interface Actions {
    inc: (delta?: number) => void;
    dec: (delta?: number) => void;
    set: (value: number | ((c: number) => number)) => void;
    reset: () => void;
}
export type ValueParam = number | ((c: number) => number);
declare function useCounter(initialValue?: number, options?: Options): readonly [number, {
    readonly inc: (this: unknown, delta?: number) => void;
    readonly dec: (this: unknown, delta?: number) => void;
    readonly set: (this: unknown, value: ValueParam) => void;
    readonly reset: (this: unknown) => void;
}];
export default useCounter;
/

SSR considerations

This hook is safe to import during SSR. If your effect body touches the DOM, keep that work inside the effect callback.

Browser compatibility

Works in any modern browser supported by Preact.