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
| Name | Type | Default | Description |
|---|---|---|---|
initialValue | number | 0 | Starting value |
options.min | number | - | Minimum allowed value |
options.max | number | - | Maximum allowed value |
Return Values
| Name | Type | Description |
|---|---|---|
count | number | Current numeric state |
increment | () => void | Increases count by 1 |
decrement | () => void | Decreases count by 1 |
reset | () => void | Returns to initial value |
set | (value: number) => void | Set 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
}