UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

45 lines (44 loc) 1.79 kB
import { useMemo } from 'react'; import { useMediatedState, useSyncedRef } from '..'; import { resolveHookState } from "../util/resolveHookState.js"; /** * Tracks a numeric value. * * @param initialValue The initial value of the counter. * @param max The maximum value the counter is allowed to reach. * If `initialValue` is greater than `max`, then `max` is set as the initial value. * @param min The minimum value the counter is allowed to reach. * If `initialValue` is smaller than `min`, then `min` is set as the initial value. */ export function useCounter(initialValue, max, min) { if (initialValue === void 0) { initialValue = 0; } var _a = useMediatedState(initialValue, function (v) { if (typeof max !== 'undefined') { v = Math.min(max, v); } if (typeof min !== 'undefined') { v = Math.max(min, v); } return v; }), state = _a[0], setState = _a[1]; var stateRef = useSyncedRef(state); return [ state, useMemo(function () { return ({ get: function () { return stateRef.current; }, set: setState, dec: function (delta) { if (delta === void 0) { delta = 1; } setState(function (val) { return val - resolveHookState(delta, val); }); }, inc: function (delta) { if (delta === void 0) { delta = 1; } setState(function (val) { return val + resolveHookState(delta, val); }); }, reset: function (val) { if (val === void 0) { val = initialValue; } setState(function (v) { return resolveHookState(val, v); }); }, }); }, [initialValue, setState, stateRef]), ]; }