Create a Memoized Function with React useCallback

Ryan Harris
InstructorRyan Harris

Share this video with your friends

Send Tweet
Published 2 years ago
Updated 2 years ago

Similar to useMemo, the useCallback hook also uses memoization internally in order to improve application performance. The difference is the type of value the two hooks return: while useMemo returns a memoized value, useCallback returns a memoized function.

This allows you to create memoized functions and pass them as props between components without having to repeatedly define the caching mechanism in order to avoid expensive, repetitive computations:

// Returns a memoized function
const memoizedFunction = useCallback(() => {
	// Define function logic
}, [data])

Ryan Harris: [0:00] Let's start by adding a useCalback Hook. We'll say const createCoordsForMap = useCallback. Like a number of the other hooks we've covered, it takes two arguments, an anonymous function and a dependency array. Our dependency array is going to have two values, locations and inputValue.

[0:24] Let's take the logic from the useMemo hook and add it to our useCallback. We'll need to make a few changes here because we're no longer setting a local state, so let's get rid of the setCoordData call. Instead, we're going to be returning the result of these filters in Maps, so let's return this directly. Since this is wrapped in an if statement, we'll need to make sure to return an empty array if there are no locations.

[0:52] As you may noticed, the map is still blank, even though we've defined our useCallback hook. That's because we need to come down here and pass a few props into our Map component.

[1:01] First, let's pass on the list of locations from our parent component. Then, we'll also pass in the inputValue that we're storing in our local state here. Last but not least, we'll pass down the memoized function createCoordsForMap, createCoordsForMap = {createCoordsForMap}.

[1:25] If we come into our Map component here, you can see that our coords variable has a placeholder of an empty array just to make sure that our app renders. However, now that we're passing in this createCoordsForMap function, we can replace this and just pass in locations and inputValue. When we save, you'll see that our coordinates are being plotted on the map.

[1:50] In summary, the difference between useCallback and useMemo is that useCallback returns a memoized function. This allows you to pass the function between components while still getting the optimization and benefits that come along with using memoization.