thanks for your time.
In this simple codesandbox. I try to memorize the value return by a function.
In my understanding, useMemo memorize the return value, which is always 2, even if count change, if the return value is the same, useMemo shouldn’t be call again.
const label = useMemo(() => {
console.log("call");
return 2;
}, [count]);
However, in the sandbox, when user clicks and count increase, "call" is still being printed and useMemo is call. Why?
2
Answers
In your code, the useMemo hook is used to memoize a value based on a function and its dependencies. The dependency array, [count], specifies when the memoized value should be recalculated. When any dependency changes, the function inside useMemo is re-evaluated.
In your specific example, the function is called every time the "Press Me" button is clicked because the count dependency changes with each click. Even though the function always returns 2, React doesn’t assume that and still calls the function to check if the result has changed.
To avoid the function being called on each click, you can use useMemo with an empty dependency array or memoize the value outside the component to ensure the function is only called once during the component’s initialization. This way, you can truly memoize the value and prevent unnecessary re-evaluation.
This is normal, as you set
count
in the dependencies array of useMemo.Acutally, whenever one of its dependency change, the useMemo is refreshed.
Therefore, whenever count change, the label value is recalculated and console.log is triggered
To fix your codesandbox, remove
count
for the useMemo dependencies array like this:More info here: https://react.dev/reference/react/useMemo