@mirawision/reactive-hooks
Version:
A comprehensive collection of 50+ React hooks for state management, UI interactions, device APIs, async operations, drag & drop, audio/speech, and more. Full TypeScript support with SSR safety.
48 lines (47 loc) • 1.77 kB
JavaScript
;
Object.defineProperty(exports, "__esModule", { value: true });
exports.useNumber = useNumber;
const react_1 = require("react");
/**
* A hook that manages numeric state with optional min/max limits and step size.
* All operations (set, inc, dec) automatically clamp the value within limits.
*
* @param initial Initial numeric value
* @param opts Options for limits and step size
* @returns Object containing value and control functions
*
* @example
* const { value, inc, dec } = useNumber(0, { min: 0, max: 10, step: 2 });
*/
function useNumber(initial = 0, opts = {}) {
const { min = -Infinity, max = Infinity, step = 1 } = opts;
// Clamp function
const clampValue = (0, react_1.useCallback)((value) => {
return Math.min(Math.max(value, min), max);
}, [min, max]);
// Initialize with clamped value
const [value, setValue] = (0, react_1.useState)(() => clampValue(initial));
// Set with automatic clamping
const set = (0, react_1.useCallback)((newValue) => {
setValue(clampValue(newValue));
}, [clampValue]);
// Increment with optional custom step
const inc = (0, react_1.useCallback)((customStep) => {
setValue(current => clampValue(current + (customStep ?? step)));
}, [clampValue, step]);
// Decrement with optional custom step
const dec = (0, react_1.useCallback)((customStep) => {
setValue(current => clampValue(current - (customStep ?? step)));
}, [clampValue, step]);
// Manual clamp (rarely needed since other operations auto-clamp)
const clamp = (0, react_1.useCallback)(() => {
setValue(current => clampValue(current));
}, [clampValue]);
return {
value,
set,
inc,
dec,
clamp,
};
}