Memoization Hooks

Learn about ”memoization” hooks provided by React Hooks API. This lesson will cover the “useCallback” hook and “useMemo” hook examples.

What is it?

React API provides two hooks to provide the memoization feature for expensive calculations. The following two hooks will be discussed in this lesson:

  • useCallback
  • useMemo

Memoization is an optimization technique to store the result of an expensive calculation for a given input. The cached result is returned for the subsequent function calls as long as the same input occurs again.

Both useCallback and useMemo provide similar functionality but with one main difference mentioned below:

  • Use the useCallback hook when wanting to memoize the callback function. This callback may perform several actions when invoked.

  • Use useMemo hook when wanting to memoize output returned from an expensive compute function. This compute function may perform heavy calculations on each function call.

When do we use it?

Use memoization hooks only when there are benefits in terms of rendering performance. For example, when rendering large lists, a memoized result may speed up the actual rendering performance.

For simple cases, it is not required to use memoization because the overhead may not offset the performance improvement.

Syntax

useCallback hook accepts two arguments: An inline callback function and an array of dependencies. useCallback returns a memoized reference to the callback function when the dependencies do not change.

const memoizedCallback = useCallback(
  () => {
    calculateFn(input);
  },
  [input],
);

Similarly, useMemo hook accepts two arguments: A callback that returns the result of an expensive compute function and an array of dependencies. useMemo returns the last cached result if the dependencies do not change.

const memoizedValue = useMemo(() => getExpensiveCalculationResult(input), [input]);

Get hands-on with 1400+ tech skills courses.