You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
46 lines
1.1 KiB
46 lines
1.1 KiB
2 years ago
|
import { useState, useRef, useEffect } from 'react';
|
||
|
|
||
|
function areInputsEqual(newInputs, lastInputs) {
|
||
|
if (newInputs.length !== lastInputs.length) {
|
||
|
return false;
|
||
|
}
|
||
|
|
||
|
for (var i = 0; i < newInputs.length; i++) {
|
||
|
if (newInputs[i] !== lastInputs[i]) {
|
||
|
return false;
|
||
|
}
|
||
|
}
|
||
|
|
||
|
return true;
|
||
|
}
|
||
|
|
||
|
function useMemoOne(getResult, inputs) {
|
||
|
var initial = useState(function () {
|
||
|
return {
|
||
|
inputs: inputs,
|
||
|
result: getResult()
|
||
|
};
|
||
|
})[0];
|
||
|
var isFirstRun = useRef(true);
|
||
|
var committed = useRef(initial);
|
||
|
var useCache = isFirstRun.current || Boolean(inputs && committed.current.inputs && areInputsEqual(inputs, committed.current.inputs));
|
||
|
var cache = useCache ? committed.current : {
|
||
|
inputs: inputs,
|
||
|
result: getResult()
|
||
|
};
|
||
|
useEffect(function () {
|
||
|
isFirstRun.current = false;
|
||
|
committed.current = cache;
|
||
|
}, [cache]);
|
||
|
return cache.result;
|
||
|
}
|
||
|
function useCallbackOne(callback, inputs) {
|
||
|
return useMemoOne(function () {
|
||
|
return callback;
|
||
|
}, inputs);
|
||
|
}
|
||
|
var useMemo = useMemoOne;
|
||
|
var useCallback = useCallbackOne;
|
||
|
|
||
|
export { useCallback, useCallbackOne, useMemo, useMemoOne };
|