useCounter

Tags:

A React hook that provides a counter with increment, decrement, and reset functionalities.

Scenes

  • Number computation scenes: Offers functionalities to increment, decrement, set, get, and reset the counter
  • UI interaction scenes: Implements the dynamic update and display of quantities on the user interface, such as the number of products in a shopping cart, carousel switching
  • Limiting value range scenes: Applies maximum and minimum value restrictions to the number (it is recommended to use the more semantically clear useClamp)
  • ...

Demo

Source
Count:
1
Min:
0
Max:
20
Initial:
1

Usage

const [count, actions] = useCounter(20) const [count, actions, couterState] = useCounter(20, { min: 1, max: 100 }) // Increment the counter actions.inc() actions.inc(2) // Decrement the counter actions.dec() actions.dec(4) // Set the counter to a specific value actions.set(10) // Reset the counter to the initial value (or reset the initial value as well) actions.reset() actions.reset(12) // Get the value of the counter, the value is count acitons.get()

Source

Click links below to view source on GitHub.

API

const [count, actions, couterState] = useCounter(initialCount, options)

InitialCount

A number type of initial value.

Options

export type UseCounterOptions = { /** * The maximum value of the counter */ max?: number /** * The minimum value of the counter */ min?: number }

Returns

export interface UseCounterReturnsAction { /** * Increment the counter */ inc: (delta?: number) => void /** * Decrement the counter */ dec: (delta?: number) => void /** * Set the counter */ set: (value: number) => void /** * Get the counter */ get(): number /** * Reset the counter */ reset: (n?: number) => void } export interface UseCounterState { /** * The value of the counter */ count: number /** * The maximum value of the counter */ max: number /** * The minimum value of the counter */ min: number /** * The initial value of the counter */ initialCount: number } export type UseCounterReturns = readonly [ /** * The count state of the counter */ number, /** * Functions to control the counter */ UseCounterReturnsAction, /** * The full internal state of the counter */ UseCounterState, ]