rooks
Version:
Essential React custom hooks ⚓ to super charge your components!
68 lines (67 loc) • 1.96 kB
JavaScript
import { useCallback, useState } from "react";
/**
*
* @typedef handler
* @type {object}
* @property {number} value The value of the counter
* @property {Function} increment Increment counter value by 1
* @property {Function} decrement Decrement counter value by 1
* @property {Function} incrementBy Increment counter by incrAmount
* @property {Function} decrementBy Decrement counter by decrAmount
* @property {Function} reset Reset counter to initialValue
* @see {@link https://react-hooks.org/docs/useCounter}
*/
/**
* Counter hook
*
* @param {number} initialValue The initial value of the counter
* @returns {handler} A handler to interact with the counter
* @see https://react-hooks.org/docs/useCounter
*/
function useCounter(initialValue) {
var _a = useState(initialValue), counter = _a[0], setCounter = _a[1];
/**
* Increment counter by an amount
*
* @param {number} incrAmount
*/
var incrementBy = useCallback(function (incrAmount) {
setCounter(function (currentCounter) { return currentCounter + incrAmount; });
}, []);
/**
*
* Decrement counter by an amount
*
* @param {*} decrAmount
*/
var decrementBy = useCallback(function (decrAmount) {
incrementBy(-decrAmount);
}, [incrementBy]);
/**
* Increment counter by 1
*/
var increment = useCallback(function () {
incrementBy(1);
}, [incrementBy]);
/**
* Decrement counter by 1
*/
var decrement = useCallback(function () {
incrementBy(-1);
}, [incrementBy]);
/**
* Reset counter to initial value
*/
var reset = useCallback(function () {
setCounter(initialValue);
}, [initialValue]);
return {
decrement: decrement,
decrementBy: decrementBy,
increment: increment,
incrementBy: incrementBy,
reset: reset,
value: counter,
};
}
export { useCounter };