@storm-stack/hooks
Version:
A collection of React hooks used by Storm Software in various client libraries and applications.
33 lines (32 loc) • 878 B
JavaScript
import { useEffect, useRef, useState } from "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;
};
export function useMemoStable(getResult, inputs) {
const initial = useState(() => ({
inputs,
result: getResult()
}))[0];
const isFirstRun = useRef(true);
const committed = useRef(initial);
const useCache = isFirstRun.current || Boolean(
inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs)
);
const cache = useCache ? committed.current : {
inputs,
result: getResult()
};
useEffect(() => {
isFirstRun.current = false;
committed.current = cache;
}, [cache]);
return cache.result;
}