Abstract

The React docs say that useCallback:

Returns a memoized callback.

And that useMemo:

Returns a memoized value.

In other words, useCallback gives you referential equality between renders for functions. And useMemo gives you referential equality between renders for values.

useCallback and useMemo both expect a function and an array of dependencies. The difference is that useCallback returns its function when the dependencies change while useMemo calls its function and returns the result.

Since JavaScript has first-class functions, useCallback(fn, deps) is equivalent to useMemo(() => fn, deps) .

Translation

Let’s understand and explain the abstract description above using simple examples. I’ll go over everything, but feel free to skip what you already know.

First-class functions

We said that in JavaScript functions are first-class. This means in JavaScript you can assign a function to a value.

Storing functions in variables enables you to use them as (the cursive points are important for React Hooks):

arguments to other functions,

return values from functions,

values to an object’s keys,

values in an array,

even as keys to the Map object.

Functions that return functions or take functions as input are called Higher-Order Functions.

Referential equality

If you use JavaScript, you probably know that there are two equality comparison operators. == for abstract equality and === for strict equality. JavaScript’s equality can be weird, and there are many great articles already written about this topic. Go read those for an in-depth look as I will only cover the basic cases relevant for useCallback and useMemo .

Referential equality uses strict equality comparison which is true if the operands are of the same type and the contents match.

Notice how foo === sameFoo returns false (contrary to greeting === otherGreeting ). This is because

two distinct objects are never equal for either strict or abstract comparisons, an expression comparing objects is only true if the operands reference the same object, and functions are objects in JavaScript.

foo and sameFoo have the same definition but reference two different objects.

API

The APIs of useCallback and useMemo look similar. They both take in a function and an array of dependencies.

useCallback(fn, deps);

useMemo(fn, deps);