Skip to content

Latest commit

 

History

History

counter

Folders and files

NameName
Last commit message
Last commit date

parent directory

..
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

useCounter()

Bundlephobia Types Build status NPM Version MIT License

npm i @react-hook/counter

A React hook counter with min/max/step/cast options

Quick Start

import useCounter from '@react-hook/counter'

const Component = () => {
  const counter = useCounter(5 /*initialValue*/, {
    min: 0,
    max: 10,
    // Sets the value to the maximum value when
    // the min value threshold has been crossed
    onMin: (set) => set(10),
    // Sets the value to the minimum value when
    // the max value threshold has been crossed
    onMax: (set) => set(0),
  })

  return (
    <div>
      <div>Value: {counter.value}</div>
      <div>
        <button onClick={() => counter.decr()}>-</button>
        {' / '}
        <button onClick={() => counter.incr()}>+</button>
      </div>
    </div>
  )
}

API

useCounter(initialValue, options)

Argument Type Default Required? Description
initialValue number 0 Yes The initial value of the counter
options UseCounterOptions See UseCounterOptions No Options for the counter

UseCounterOptions

Option Type Default Description
min number undefined The minimum counter value
max number undefined The maximum counter value
step number 1 The amount to increment/decrement the counter by, by default when incr or decr are called
cast (value: number) => number Number Casts the number to a specific type, e.g. parseFloat, parseInt, etc.
onMin (set: (value: number) => void) => void undefined Called when a user tries to set a value below the min value defined above. By default the value will just not change once the min is exceeded.
onMax (set: (value: number) => void) => void undefined Called when a user tries to set a value above the max value defined above. By default the value will just not change once the max is exceeded.

UseCounterState

Option Type Description
value number The current value of the counter
set (value: number) => void Sets a new value to the counter
incr (by: number = step) => void Increments the value of the counter by step by default
decr (by: number = step) => void Decrements the value of the counter by step by default

LICENSE

MIT