UNPKG

@supunlakmal/hooks

Version:

A collection of reusable React hooks

48 lines 2.26 kB
import { useCallback } from 'react'; import { useLocalStorage } from './useLocalStorage'; /** * A hook that provides a counter state that persists in local storage, * supporting min, max, and step options. * * @param key The key to use in local storage. * @param initialValue The initial value for the counter if not found in storage, defaults to 0. * @param options Options for the counter (min, max, step). * @returns An object containing the current count and counter manipulation functions. */ export function usePersistentCounter(key, initialValue = 0, options) { const [count, setCount] = useLocalStorage(key, initialValue); // Destructure options with default step const { min, max, step = 1 } = options !== null && options !== void 0 ? options : {}; const increment = useCallback(() => { setCount((currentCount) => { const newValue = currentCount + step; // Apply max constraint if defined if (max !== undefined && newValue > max) { return currentCount; // Or return max; depends on desired behavior } return newValue; }); }, [setCount, max, step]); const decrement = useCallback(() => { setCount((currentCount) => { const newValue = currentCount - step; // Apply min constraint if defined if (min !== undefined && newValue < min) { return currentCount; // Or return min; depends on desired behavior } return newValue; }); }, [setCount, min, step]); const set = useCallback((newCount) => { // Clamp the new value according to min/max if defined const clampedValue = Math.max(min !== null && min !== void 0 ? min : -Infinity, Math.min(max !== null && max !== void 0 ? max : Infinity, newCount)); setCount(clampedValue); }, [setCount, min, max]); const reset = useCallback(() => { // Reset sets back to the initial value provided to the hook setCount(initialValue); }, [setCount, initialValue]); // Return the state from useLocalStorage and the newly defined functions return { count, increment, decrement, set, reset }; } //# sourceMappingURL=usePersistentCounter.js.map