UNPKG

@react-hookz/web

Version:

React hooks done right, for browser and SSR.

31 lines (30 loc) 1.36 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.usePreviousDistinct = void 0; var react_1 = require("react"); var __1 = require(".."); var const_1 = require("../util/const"); /** * Returns the most recent _distinct_ value passed to the hook on previous render. Distinct here * means that the hook's return value will only update when the passed value updates. This is * useful when other renders are involved potentially making multiple, irrelevant updates. * * Yields `undefined` on first render. * * @param value Value to yield on next render if it's different from the previous one. * @param predicate Optional predicate to determine if the value is distinct. If not provided, * the value will be updated if it is strictly equal (`===`) to the previous value. */ function usePreviousDistinct(value, predicate) { if (predicate === void 0) { predicate = const_1.isStrictEqual; } var _a = (0, react_1.useState)(), previousState = _a[0], setPreviousState = _a[1]; var currentRef = (0, react_1.useRef)(value); (0, __1.useUpdateEffect)(function () { if (!predicate(currentRef.current, value)) { setPreviousState(currentRef.current); currentRef.current = value; } }, [value]); return previousState; } exports.usePreviousDistinct = usePreviousDistinct;