Docs
Counter

Counter

Manage a counter value with minimum and maximum limits.

About

The useCounter hook is helpful for managing a counter value, offering extra options for setting minimum and maximum limits. It accepts a starting value and an options object that can define these limits. If the starting value is outside the defined limits, an error is thrown. The hook provides the current count value and an object with functions to increment, decrement, set a specific count, and reset the counter.

Parameters

NameTypeDescription
startingValuenumberThe initial value for the counter. Default is 0.
optionsobjectAdditional options for the counter.
options.minnumberThe minimum value allowed for the counter.
options.maxnumberThe maximum value allowed for the counter.

Return Values

NameParametersDescription
[0]The current value of the counter.
[1].incrementIncrements the counter by 1.
[1].decrementDecrements the counter by 1.
[1].setnextCount: numberSets the counter to the specified nextCount value.
[1].resetResets the counter to the initial startingValue.

Installation

Run the following command:

npx scriptkavi-hooks@latest add counter

Usage

import { useCounter } from "@/hooks/counter"
import * as React from "react"
 
export default function App() {
  const [count, { increment, decrement, set, reset }] = useCounter(5, {
    min: 5,
    max: 10,
  })
 
  return (
    <section>
      <h1>UseCounter</h1>
      <h6>with optional min / max</h6>
      <button disabled={count >= 10} className="link" onClick={increment}>
        Increment
      </button>
      <button disabled={count <= 5} className="link" onClick={decrement}>
        Decrement
      </button>
      <button className="link" onClick={() => set(6)}>
        Set to 6
      </button>
      <button className="link" onClick={reset}>
        Reset
      </button>
      <p>{count}</p>
    </section>
  )
}