useCallback

Learn how to optimize the performance of your applications and prevent unnecessary re-renders.

What is useCallback()?

The useCallback() Hook can be used to optimize the performance of an application. It receives a function and then creates a unique identity of that function, which will remain active until the dependencies of the Hook itself change.

This is important becasue we need to provide the same reference to a function when:

  1. Dealing with PureComponents.
  2. Functions implement their own shouldComponentUpdate() method.
  3. Functions are wrapped by React.memo().

The useCallback() Hook expects two parameters. The first is a function and the second is a dependency array (similar to that in useEffect()). It’s called in the following way:

const memoizedFunction = useCallback(callbackFunction, dependencyArray);

It will return a stable reference to the function that we passed in, meaning that the reference only changes if one of its dependencies changed. Up to this point, references to PureComponents or components with React.memo() are the same.

Example without optimization

This sounds a little complicated in theory. Let’s look at an example:

Get hands-on with 1400+ tech skills courses.