raddix

useCounter

Manage a counter with increment/decrement functions.

Features

  • Reset the counter to the initial value.
  • Set the minimum and maximum values of the counter.
  • Set the counter to a given value.
  • Execute a function when the counter reaches the minimum or maximum value.

Installation

npm i @raddix/use-counter

Usage

Counter basic

To begin, we will create a counter with the possibility of incrementing and decrementing it by 1, and resetting it to the initial value.

import { useCounter } from '@raddix/use-counter';
const Counter = () => {
const [counter, { inc, dec, reset }] = useCounter(0);
return (
<div>
<p>Counter: {counter}</p>
<button onClick={() => inc()}>Increment</button>
<button onClick={() => dec()}>Decrement</button>
<button onClick={() => reset()}>Reset</button>
</div>
);
};

Add minimum and maximum values

Now, we will add a minimum and maximum value to the counter, and execute a function when the counter reaches the minimum or maximum value.

import { useCounter } from '@raddix/use-counter';
const Counter = () => {
const [counter, { inc, dec, reset }] = useCounter(0, {
min: 0,
max: 10,
onMin: () => console.log('Counter reached the minimum value'),
onMax: () => console.log('Counter reached the maximum value')
});
return (
<div>
<p>Counter: {counter}</p>
<button onClick={() => inc()}>Increment</button>
<button onClick={() => dec()}>Decrement</button>
<button onClick={() => reset()}>Reset</button>
</div>
);
};

API

Return value

The useCounter hook returns an array with the following elements:

IndexDescriptionType
0 (counter)The current counter value.number
1 (actions)An object containing the actions to manage the counter.object

Actions

NameDescriptionType
incIncrements the counter, default by 1.(value?: number) => void
decDecrements the counter, default by 1.(value?: number) => void
resetResets the counter value to the initial value.() => void
setSets the counter value to the given value.(value: number) => void

Parameters

The useCounter hook accepts the following parameters:

NameDescriptionType
initialValueThe initial value of the counter.number
optionsAn object containing the options to manage the counter.object

Options

NameDescriptionType
minThe minimum value of the counter.number
maxThe maximum value of the counter.number
onMinFunction to execute when the counter reaches the minimum value() => void
onMaxFunction to execute when the counter reaches the maximum value() => void