Thursday, January 27, 2022

Difference between React useCallback and useMemo

React useCallback and useMemo hooks look similar, and both of them take a callback function, and dependent array as parameters. But their returns different values to the callers.

useCallback hook returns a memorized callback function, if the dependencies are changed. So the type of the variable assigned by useCallback is a function object. The function object itself is memorized, so when rendering the parent react function component, the function object will not be created again and again as new function objects. The function object body will not be invoked until in the project someone calls the function.

useMemo hook returns a memorized object, so the type of the variable assigned by useMemo may be any type depends what is returned from the callback method body in useMemo's first parameter. If nothing is returned, then the variable assigned by useMemo hook is undefined. Different from useCallback hook, when assigning a variable by useMemo hook, the callback method of useMemo hook will be called immediately, no matter whether the variable is used or not by the application. 

Since both useMemo and useEffect will automatically execute their callback method when page loads or when dependency parameters change, so their functions look similar. But useMemo is executed during DOM rendering. while use Effect is executed after DOM rendering, for the time consuming operation such as remote network requests. 

In practice, it is important in many times, the cost of using useCallback and useMemo may be bigger than the benefit bringing by it, and requirement of setting the proper dependent array parameter may introduce new bugs to the logic, so they should be used with caution in the real project.

No comments:

Post a Comment