Learn how to memoize the results of a function between renders and only call the function again when dependencies change.

Difference between useMemo() and useCallback()

The other Hook that’s useful for performance optimization is the useMemo() Hook. We call it in the following way:

const memoizedValue = useMemo(valueGetterFunction, dependencyArray);

It works similarly to the useCallback() Hook. However, it does not provide a unique identity for the function going in, but for the return value from the function, which has been passed into the useMemo() Hook.

So, the following snippet of code:

useCallback(fn, deps);

corresponds to this snippet:

useMemo(() => fn, deps);

While the useCallback() Hook returns a memoizedA “remembered” version that can be retrieved later without repeating the computation. version of the function that has been passed in, the useMemo() Hook provides a memoized version of the return value of the function that has been passed in. The useMemo() Hook can be really useful in situations where functions perform complex computational tasks that don’t need to be executed in each render.

Function component without useMemo() optimization

Let us have a look at a non-optimized component:

Get hands-on with 1200+ tech skills courses.