useCounter

A state hook for numeric values with built-in increment, decrement, and reset functions.

🧙‍♂️

Character Stats

Level 42 Archmage

Strength10/100
Agility15/100
Intelligence20/100
Total Stat Points45

Usage

import { useCounter } from 'usehooks-ts'
 
export default function App() {
  const { count, increment, decrement, reset, set } = useCounter(0, { min: 0, max: 10 })
 
  return (
    <div>
      <p>Count: {count}</p>
      <button onClick={increment}>Increment</button>
      <button onClick={decrement}>Decrement</button>
      <button onClick={reset}>Reset</button>
    </div>
  )
}

API

const { count, increment, decrement, reset, set } = useCounter(initialValue, options?)

Parameters

NameTypeDefaultDescription
initialValuenumber0Starting value
options.minnumber-Minimum allowed value
options.maxnumber-Maximum allowed value

Return Values

NameTypeDescription
countnumberCurrent numeric state
increment() => voidIncreases count by 1
decrement() => voidDecreases count by 1
reset() => voidReturns to initial value
set(value: number) => voidSet a specific value

Hook

import { useState, useCallback } from 'react'
 
export interface CounterOptions {
  min?: number
  max?: number
}
 
export function useCounter(initialValue: number = 0, options: CounterOptions = {}) {
  const [count, setCount] = useState(initialValue)
 
  const increment = useCallback(() => {
    setCount((prev) => {
      const nextValue = prev + 1
      if (options.max !== undefined && nextValue > options.max) {
        return prev
      }
      return nextValue
    })
  }, [options.max])
 
  const decrement = useCallback(() => {
    setCount((prev) => {
      const nextValue = prev - 1
      if (options.min !== undefined && nextValue < options.min) {
        return prev
      }
      return nextValue
    })
  }, [options.min])
 
  const reset = useCallback(() => {
    setCount(initialValue)
  }, [initialValue])
 
  return { count, increment, decrement, reset, set: setCount } as const
}