@react-hook/counter
TypeScript icon, indicating that this package has built-in type declarations

2.0.0 • Public • Published

useCounter()

Bundlephobia Types 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

Returns UseCounterState

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

Package Sidebar

Install

npm i @react-hook/counter

Weekly Downloads

7

Version

2.0.0

License

MIT

Unpacked Size

26.2 kB

Total Files

20

Last publish

Collaborators

  • jaredlunde