Skip to content

useCounter ​

Hook that manages a counter

utilities
test coverage
Last changed: last month

Installation ​

Library
CLI
Manual
typescript
import { useCounter } from '@siberiacancode/reactuse';

Usage ​

typescript
const { count, dec, inc, reset, set } = useCounter(5);
// or
const { count, dec, inc, reset, set } = useCounter({ initialValue: 5, min: 0, max: 10 });

Demo ​

Api ​

Parameters

NameTypeDefaultNote
initialValue?number0The initial number value
options.min?numberNumber.NEGATIVE_INFINITYThe min of count value
options.max?numberNumber.POSITIVE_INFINITYThe max of count value

Returns

UseCounterReturn

Parameters

NameTypeDefaultNote
params.initialValue?number0The initial number value
params.min?numberNumber.NEGATIVE_INFINITYThe min of count value
params.max?numberNumber.POSITIVE_INFINITYThe max of count value

Returns

UseCounterReturn

Type declaration ​

typescript
import type { Dispatch, SetStateAction } from 'react';

export interface UseCounterOptions {
  /** The max of count value */
  max?: number;
  /** The min of count value */
  min?: number;
}

export interface UseCounterReturn {
  /** Function to set a specific value to the counter */
  set: Dispatch<SetStateAction<number>>;
  /** The current count value */
  value: number;
  /** Function to decrement the counter */
  dec: (value?: number) => void;
  /** Function to increment the counter */
  inc: (value?: number) => void;
  /** Function to reset the counter to its initial value. */
  reset: () => void;
}

export interface UseCounter {
  (initialValue?: number, options?: UseCounterOptions): UseCounterReturn;

  (options: UseCounterOptions & { initialValue?: number }, initialValue?: never): UseCounterReturn;
}

Source ​

Source • Demo

Contributors ​

D
debabin
debabin

Released under the MIT License.