Demystifying React Hooks: useCallback and useMemo
Milu
Posted on June 14, 2020
React Hooks introduced the capability to use state and other lifecycle features while using functional components instead of classes. Hooks are a simpler way to encapsulate stateful behavior and side effects in a user interface while using less code and increasing readability.
Some hooks are easier to understand and use than others, therefore this series of posts will focus on demystifying the hooks that are not as straightforward. Let’s start by explaining what occurs when a component re-renders, followed by defining the purpose of useCallback and useMemo, and finally discussing when it is and when it is not appropriate to use these hooks.
What occurs when a component re-renders?
As you might already know, React re-renders components on every state change or when props change. Since functions are considered objects in JavaScript, all objects (including functions) created under a React functional component will be created again on every re-render. This occurs as a consequence of referential equality, which means that two objects that look exactly alike are not the same unless they both point at the same object.
In other words, when a React component is about to re-render, it compares each object created under its original component with the new version of itself. And even though the objects are exactly the same, they are not pointing at the same object, therefore React identifies them as different objects and it allows their re-creation all over again under each re-render.
What is the purpose of useCallback and useMemo?
The purpose of useCallback and useMemo, if used correctly, is to prevent unnecessary re-renders and make your code more efficient.
Let’s take a look at their structure. Both of these hooks receive two parameters:
1) a function
2) an array of dependencies
useCallback hook returns the same instance of the function being passed (parameter #1) instead of creating a new one every time a component re-renders.
It creates a new instance of the function being passed (parameter #1) only when the array of dependencies (parameter #2) changes.
Let’s look at an example, here we have a simple app that adds two values. The user can increment the first value and/or decrease the second value and the result will update accordingly. We also have a third extra
value that the user can update, however, this number is not being used in the computation.
If the user interacts with the extra
state value, the component would re-render creating a new copy of the additionResult function even though extraVal is not used in it. In this example, we implement the useCallback hook to only create a new copy of the additionResult function if firstVal or secondVal are updated.
useMemo hook is very similar, however, instead of returning an uncalled function as useCallback does, it calls the function being passed and only returns a result value when the array of parameters change. In other words, useMemo calls the passed function only when necessary and it returns a cached value on all the other renders.
In this example, we implemented an app that accepts a number and it returns it's factorial. For instance, if we typed the number 5, it would use a recursive function to compute 5!= 5*4*3*2*1=120. In this case, we used the useMemo hook to tell React to only recalculate when the number changes.
When to use them?
If you are thinking of adding useCallback and useMemo hooks everywhere in your component, please don’t.
Both of these hooks add some extra complexity to your code and they require a lot of things working under the hood.
Adding performance optimizations using useCallback and useMemo is expensive and these optimizations don’t always bring enough benefits to offset their cost.
You should consider using useCallback and/or useMemo hooks on the following situations:
1) Processing large amounts of data
2) Working with interactive graphs and charts
3) Implementing animations
4) Incorporating component lazy loading (useMemo specifically)
Summary
When a component is re-rendered, it creates new instances of all objects, including all the functions in it.
useCallback - Allows you to cache an instance of a function between renders.
useMemo - Allows you to cache a value between renders.
I hope you found this post helpful and that you will start using useCallback and useMemo with confidence in your next project.
I post new content every week. We will be exploring a different React hook next Sunday!
Posted on June 14, 2020
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.