Skip to main content

useCounter

useCounter is a custom React hook that provides functionality for managing a counter. It allows for incrementing, decrementing, and resetting the counter, as well as incrementing and decrementing by a specific value.

Usage

import { useCounter } from 'hookify-react';

export default function CounterComponent() {
const { count, increment, decrement, reset } = useCounter(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={increment}>Increment</button>
<button onClick={decrement}>Decrement</button>
<button onClick={reset}>Reset</button>
</div>
);
}

API Reference

Parameters

ParameterTypeDefaultDescription
initialValuenumber0The initial value of the counter.

Return Value

useCounter returns an object with the following properties:

PropertyTypeDescription
countnumberThe current value of the counter.
incrementfunctionIncrements the counter by 1.
incrementByValuefunctionIncrements the counter by a specified value.
decrementfunctionDecrements the counter by 1.
decrementByValuefunctionDecrements the counter by a specified value.
resetfunctionResets the counter to its initial value.

Example: Incrementing and Decrementing by a Specific Value

import { useCounter } from 'hookify-react';

export default function CounterComponent() {
const { count, incrementByValue, decrementByValue } = useCounter(0);

return (
<div>
<p>Count: {count}</p>
<button onClick={() => incrementByValue(5)}>Increment by 5</button>
<button onClick={() => decrementByValue(5)}>Decrement by 5</button>
</div>
);
}