2.0.0 • Published 4 years ago

@react-hook/counter v2.0.0

Weekly downloads
176
License
MIT
Repository
github
Last release
4 years ago

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)

ArgumentTypeDefaultRequired?Description
initialValuenumber0YesThe initial value of the counter
optionsUseCounterOptionsSee UseCounterOptionsNoOptions for the counter

Returns UseCounterState

UseCounterOptions

OptionTypeDefaultDescription
minnumberundefinedThe minimum counter value
maxnumberundefinedThe maximum counter value
stepnumber1The amount to increment/decrement the counter by, by default when incr or decr are called
cast(value: number) => numberNumberCasts the number to a specific type, e.g. parseFloat, parseInt, etc.
onMin(set: (value: number) => void) => voidundefinedCalled 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) => voidundefinedCalled 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

OptionTypeDescription
valuenumberThe current value of the counter
set(value: number) => voidSets a new value to the counter
incr(by: number = step) => voidIncrements the value of the counter by step by default
decr(by: number = step) => voidDecrements the value of the counter by step by default

LICENSE

MIT