Beginner's Guide to React useCallback Hook
Learn about the useCallback Hook, its use cases and implementation.
Hook: useCallback
#
In a similar fashion to the useMemo
Hook, useCallback
gives us a means to optimize our applications somewhat. It also provides a form of memoization.
However, the big difference between the two Hooks is that useMemo
provides a way to memoize a value, whilst useCallback
memoizes a function. It looks and feels almost identical to the implementation of useMemo
too. You define and use the useCallback
Hook like this:
const someMemoizedCallback = useCallback(() => {
// run a function here
myEpicFunction(depOne, depTwo);
// passed in dependencies
}, [depOne, depTwo]);
Memoizing functions#
"Great", you’re thinking, "but why would anyone want to memoize a callback function?"
Well, the complicated answer is "it depends".
Let’s start with a little 101 on React components. Each time a component re-renders, React will create new versions of items like function objects. Take the following code snippet as an example:
function MyEpicComponent() {
const handleButtonClick = () => {
// ...do something in here
};
// ...rest of component
}
Each time MyEpicComponent
re-renders, handleButtonClick
is recreated as a brand-new function object. For most components this isn’t a problem and is usually nothing that you need to concern yourself with; this re-creating of functions is inexpensive and not going to cause you any problems, performance-based or otherwise.
However, there are some situations you might face where you don’t want this behavior. One such example might be when the function is a dependency of other Hooks. In this situation, you’d want to have access to the same function object across different renderings, not some brand-new instance (or we’d be back in infinite looping territory again).
In essence, given the same dependency values, useCallback
returns the same function instance between renders.
Further reading on useCallback#
You can discover more on the useCallback
Hook at the official React docs website. Once you’ve checked those out, I’d also recommend the following articles:
Dmitri Pavlutin’s guide to
useCallback
When to use
useCallback
by Ahead CreativeAnd an article from Kent C Dodds
Building the useCallback example#
The useCallback
Hook is one of those tools that you may not use or come across a great deal, but when you do need to use it, the benefits are huge. Because of the rather infrequent need to use this Hook, our example is going to be a little more contrived, in order to highlight those benefits.
We’ll be building a message generator and some buttons that increment counters within the component. We will keep track of the functions that our component recreates across each render so you can see how useCallback
comes into play.
Let’s start by opening the UseCallbackExample.jsx
file and building it out.
Imports and external variables#
First things first, we’ll need to import React, useState
and of course, the useCallback
Hook.
import React, { useState, useCallback } from 'react';
Next, we need a couple of constants that will live outside of our main component:
const messages = [
'Hello dear, what a lovely day outside',
'The 2 best times to learn React were yesterday, and today!',
'Thanks for studying React with The Beginners Guide to React',
'Some people, Master Bruce, just want to watch the world burn',
'And nothing lasts forever, like the cold november rain'
];
const functionStore = new Set();
We have a simple array of string messages that we’ll use within our component. With functionStore
we’re creating a shiny new instance of a Set object. You can store lists or collections of anything you like in a Set object, but the key part here is that Set naturally keeps things unique for us. The importance of this will become apparent in a little while.
Defining the default exported component#
This page is a preview of Beginner's Guide to Real World React