useCallback hook in React


Objectives

Learn how to use the useCallback hook.

useCallback

useCallback is to prevent a component from re-rendering unless its dependencies change. This allows us to isolate resource intensive functions so that they will not automatically run on every render. You might be thinking, "What's the difference between useCallback and useMemo?" Well, useCallback is used to memoize functions, while useMemo is used to memoize values. Check out my previous post on useMemo if you want to learn more about it.

useCallback

Problem

Let's say we have a component that renders a list of random numbers. We want to be able to add a new random number to the list when we click a button.

Here, we have a parent component that renders the child component <Number/>. As above mentioned, the child component renders a list of random numbers. The parent component has a button that increments a counter. The child component has a button that adds a new random number to the list.

Let's see what happens when we click the button in the parent component.

The problem is that every time we click the button in the parent component, the child component re-renders.

This is not ideal because we don't want the child component to constantly re-render. We only want the child component to re-render when the list changes. Let's fix this problem with useCallback.

useCallback

In the code below, we wrap the function that adds a new random number to the list with useCallback. This will prevent the function from being re-created on every render. The function will only be re-created when the list changes.

Now, when we click the button in the parent component, the child component does not re-render.

Hooray for useCallback! Now, we can isolate resource intensive code so that it will not automatically run on every render.

Conclusion

That's it! useCallback isn't too complicated. It's just a hook that prevents a component from re-rendering unless its dependencies have changed. Thank you for reading! I hope you learned something new! If you have any questions or comments, please feel free to leave them below! I'll see you in the next one!

Resources