Published

What is the difference between useCallback and useMemo in React?

If you've worked with React Hooks, you've probably wondered what's the difference between useCallback and useMemo. Both functions are used to memoize values and prevent them from being recalculated on each rendering, but when should we use one or the other?

First, it is important to understand that useCallback and useMemo expect a function and an array of dependencies as arguments. The difference is that useCallback returns its memoized function when the dependencies change, while useMemo calls its function and returns the result.

In other words, useCallback gives you referential equality between renderings for functions, while useMemo gives you referential equality between renderings for values.

In API terms, the two functions are very similar. For example, useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).

But when should we use each of them? In general, we should use useCallback when we depend on referential equality between renderings for functions, and useMemo when we depend on referential equality between renderings for values.

For example, if we have a function that makes a request to an API and depends on a parameter, we can use use useCallback to memoize the function and ensure that it is not recalculated on each rendering unless the parameter changes.

const fetchData = useCallback((id) => {
  // Makes a request to the API using the id
}, [id]);

On the other hand, if we want to calculate a value from a set of data and make sure that it is not recalculated at each rendering, we can use useMemo.

const filteredData = useMemo(() => {
  // Calculates a value from data
}, [data, query]);

In summary, useCallback and useMemo are two powerful tools that allow us to memoize functions and values in React. If we depend on referential equality between renderings for a function, we must use useCallback, and if we depend on referential equality between renderings for a value, we must use useMemo.

Thanks for reading this far ❤️