UNPKG

@storm-stack/hooks

Version:

A collection of React hooks used by Storm Software in various client libraries and applications.

36 lines (35 loc) 1.01 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.useMemoStable = useMemoStable; var _react = require("react"); const areInputsEqual = (newInputs, lastInputs) => { if (newInputs.length !== lastInputs.length) { return false; } for (const [i, newInput] of newInputs.entries()) { if (newInput !== lastInputs[i]) { return false; } } return true; }; function useMemoStable(getResult, inputs) { const initial = (0, _react.useState)(() => ({ inputs, result: getResult() }))[0]; const isFirstRun = (0, _react.useRef)(true); const committed = (0, _react.useRef)(initial); const useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs)); const cache = useCache ? committed.current : { inputs, result: getResult() }; (0, _react.useEffect)(() => { isFirstRun.current = false; committed.current = cache; }, [cache]); return cache.result; }