What's the difference between useCallback and useMemo in practice?

后端 未结 4 1809
半阙折子戏
半阙折子戏 2020-12-02 04:40

Maybe I misunderstood something, but useCallback Hook runs everytime when re-render happens.

I passed inputs - as a second argument to useCallback - non-ever-changea

4条回答
  •  北荒
    北荒 (楼主)
    2020-12-02 05:31

    You are calling the memoized callback every time, when you do:

    const calcCallback = useCallback(() => expensiveCalc('useCallback'), [neverChange]);
    const computedCallback = calcCallback();
    

    This is why the count of useCallback is going up. However the function never changes, it never *****creates**** a new callback, its always the same. Meaning useCallback is correctly doing it's job.

    Let's making some changes in your code to see this is true. Let's create a global variable, lastComputedCallback, that will keep track of if a new (different) function is returned. If a new function is returned, that means useCallback just "executed again". So when it executes again we will call expensiveCalc('useCallback'), as this is how you are counting if useCallback did work. I do this in the code below, and it is now clear that useCallback is memoizing as expected.

    If you want to see useCallback re-create the function everytime, then uncomment the line in the array that passes second. You will see it re-create the function.

    'use strict';
    
    const { useState, useCallback, useMemo } = React;
    
    const neverChange = 'I never change';
    const oneSecond = 1000;
    
    let lastComputedCallback;
    function App() {
      const [second, setSecond] = useState(0);
      
      // This 

提交回复
热议问题