I have the trouble resolving the issue described below.
I tried to use useMemo
, but seems like I’m using it in a wrong way.
I’ve created custom hook that should do some expensive calculation on a huge object and return it, used useMemo
hook to reduce re-calculations:
// just for example
// retreived api call or some other place, not generated here
const hugeData = new Array(100).fill(1000);
const useCalculationHook = (dependency) => {
// useMemo will should only re-calculate when dependency changes
const sum = useMemo(() => {
console.log("re-calculated", dependency);
return expensiveCalculation(hugeData, dependency);
}, [dependency]);
return sum;
};
I whant the hook above to return the already calculated result when given the same dependency.
useCalculationHook(1) // re-calculate
useCalculationHook(2) // re-calculate
useCalculationHook(3) // re-calculate
useCalculationHook(1) // return cached-result
The results are saved between re-renders and that really gives the boost to my app when I render a huge list of the component that uses the useCalculationHook
but initial re-calculation happens every time no matter what I give as dependency.
I know that that I can do it manually by saving the results in object and using it, but if there is a “React” way I definitely prefer to implement that.
Or… is there any library where I can manually cache results?
Example on Codesandbox * See the console to see when it re-calculates the useMemo.