React Hooks — useCallback and useMemo

Sean Hsieh-yoyo
2 min readJun 2, 2022

useCallback, useMemo

  • What

useCallback: returns a memorized callback.

useMemo: returns a memorized value.

***these two hooks help us to avoid re-creating and re-running the functions

  • Why & How?

Functional Components fundamentally are the same as the render function in class components. According to this, when a function is defined inside a functional component, it will be re-created and re-evaluated on every re-render.

In addition, if a functional parent component has a function passed as a property to a child component, it will cause its child to re-render no matter what.

In JavaScript, a function is an object and react component will re-render if its props or state changes. If you define a function(object) inside a react functional component, it is not going to be the same function(object) you have defined before between re-renders, which results in referential inequality.

Because of this reason, everytime when you change the App component’s state, the random function is re-created.

To solve this problem and prevent possible performance issues, we can use useCallback & useMemo. Let’s see how we can take advantage of these two methods.

  • useMemo

useMemo is to memorize a calculation result between a function’s calls and between renders

useMemo receives two params:

  • A callback function
  • An array of dependencies:

***Conceptually, every value referenced inside the callback should also appear in the dependencies array.

useMemo prevents the callback function from being return if there are no changes in the dependency array.

Use it when you want to avoid heavy calculations

  • useCallback

useCallback is to memorize a callback itself (referential equality) between renders

This hook focuses on a different thing. it is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.

This hook will preserve and only re-created our function when there are any changes in the dependency array.

Use it if you want referential equality between renders when you pass a function as a property to child component

  • When

Everything has two sides, so does performance optimization. What costs us here with useCallback is that our function is not removed in memory, use it when you want to avoid redundant renders of child components.

With useMemo, it should be used when we need to cache expensive calculations whose dependencies change gradually

Reference:

--

--