skip to Main Content

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


  1. 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.

    Login or Signup to reply.
  2. 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 countfor the useMemo dependencies array like this:

      const label = useMemo(() => {
        console.log("call");
        return 2;
      }, []);
    

    More info here: https://react.dev/reference/react/useMemo

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search