Hello! Welcome back to our module on performance optimization.
In our last lesson on useMemo, we tackled a major performance hurdle: preventing unnecessary re-renders of memoized components by preserving the referential identity of objects and arrays passed as props. However, we left one crucial piece of the puzzle unsolved. What happens when we pass a function as a prop?
Today, we will address exactly that. This lesson focuses on the useCallback hook, the specific tool designed to memoize function definitions. You'll learn how to use it to prevent unnecessary re-renders in child components, making your React.memo optimizations truly effective.
The Problem: Referential Equality of Functions
As you know from your computer science background, functions in JavaScript are first-class citizens, meaning they behave like objects. And just like objects and arrays, they are compared by reference, not by value.
This means that every time a React component renders, any function defined inside its body is a brand new function instance, even if the code is identical to the one from the previous render.
// This will always be false, as they are two separate function objects in memory.
(function() {}) === (function() {}) // false
This behavior breaks the shallow prop comparison performed by React.memo, causing child components to re-render even when nothing has visibly changed.
Let's watch a demonstration of this exact problem.
Learn React Hooks: useCallback - Simply Explained!
The video 'Learn React Hooks: useCallback - Simply Explained!' by Cosden Solutions sets up a perfect scenario to illustrate this issue. It features a parent component with a shuffle button that updates its state, and a memoized child Search component that receives a function prop.
Watch from 00:34 to 08:13. Pay close attention to the console. Notice that even though the Search component is wrapped in React.memo and its functionality is unrelated to shuffling users, it still re-renders every time the 'Shuffle' button is clicked. The video does an excellent job of explaining why this happens due to the function prop being recreated.
As the video demonstrates, the handleSearch function gets a new memory address on every render of the parent component. When this new function reference is passed as the onChange prop, React.memo sees it as a new prop and correctly decides to re-render the Search component.
The Solution: useCallback
To solve this, React provides the useCallback hook. Its entire purpose is to return a memoized version of a function that only changes if one of its dependencies has changed. This gives you a stable function reference across re-renders.
The syntax is very similar to useMemo:
const memoizedCallback = useCallback(
() => {
// function logic...
doSomething(dependency);
},
[dependency], // The dependency array
);
useCallback as Syntactic Sugar
Here's a key insight that will solidify your understanding by connecting it to our previous lesson: useCallback is just syntactic sugar for useMemo.
The following two lines are functionally equivalent:
// Using useCallback
const myFn = useCallback(() => { console.log('hello'); }, []);
// Using useMemo
const myFn = useMemo(() => () => { console.log('hello'); }, []);
useCallback(fn, deps) is the same as useMemo(() => fn, deps). It's a convenient shorthand specifically for memoizing functions.
Understanding useMemo and useCallback
The article 'Understanding useMemo and useCallback' by Josh W. Comeau explains this relationship very clearly.
Read the section 'The useCallback hook'. It provides a great example and directly explains how useCallback is a more convenient version of useMemo for functions.
Now, let's see how applying useCallback solves the re-render problem from the video.
Learn React Hooks: useCallback - Simply Explained!
Continuing with the 'Cosden Solutions' video, let's see the fix in action.
Watch from 08:13 to 10:20. Observe how wrapping handleSearch in useCallback with an empty dependency array ([]) now prevents the Search component from re-rendering when the users are shuffled.
Test your understanding!
You have a Parent component with a theme state and a memoized Button component. Every time you toggle the theme, the Button re-renders, which is unnecessary.
// Button.tsx
import React from 'react';
interface ButtonProps {
onClick: () => void;
children: React.ReactNode;
}
const Button: React.FC<ButtonProps> = ({ onClick, children }) => {
console.log(`Rendering button: ${children}`);
return <button onClick={onClick}>{children}</button>;
};
export default React.memo(Button);
// Parent.tsx
import React, { useState } from 'react';
import Button from './Button';
const Parent: React.FC = () => {
const [theme, setTheme] = useState('light');
const handleButtonClick = () => {
alert('Button clicked!');
};
const toggleTheme = () => {
setTheme(current => (current === 'light' ? 'dark' : 'dark'));
};
return (
<div>
<Button onClick={handleButtonClick}>Click Me</Button>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
How would you modify the Parent component to prevent the Button from re-rendering when the theme is toggled?
Show answer
You need to wrap handleButtonClick in useCallback with an empty dependency array. This ensures that the Button component receives the exact same onClick prop reference across re-renders caused by the theme change.
// Parent.tsx (fixed)
import React, { useState, useCallback } from 'react'; // Import useCallback
import Button from './Button';
const Parent: React.FC = () => {
const [theme, setTheme] = useState('light');
// Wrap the function in useCallback
const handleButtonClick = useCallback(() => {
alert('Button clicked!');
}, []); // Empty dependency array because it doesn't depend on any state or props
const toggleTheme = () => {
setTheme(current => (current === 'light' ? 'dark' : 'light'));
};
return (
<div>
<Button onClick={handleButtonClick}>Click Me</Button>
<button onClick={toggleTheme}>Toggle Theme</button>
</div>
);
};
The Most Common Pitfall: Stale Closures
Memoizing a function with an empty dependency array ([]) can introduce a subtle but significant bug: the stale closure.
When you memoize a function, it "closes over" the state and props from the render in which it was created. If you provide [] as the dependencies, the function is created only once on the initial render and is never updated. If that function relies on a piece of state, it will forever see the initial value of that state, not its current value.
This is arguably the most important concept to master when using useCallback.
Learn React Hooks: useCallback - Simply Explained!
The Cosden Solutions video has a truly exceptional demonstration of this pitfall and how to fix it.
Watch from 10:20 to 16:33. The example modifies the handleSearch function to log the first user from the users state array. First, you'll see the bug in action: the logged user is always 'John' (the initial state), even after the list is filtered. This is a stale closure. Then, you'll see the fix: adding users to the dependency array, which tells React to re-create the memoized function whenever the users state changes.
The rule is simple: The dependency array of useCallback must include every reactive value (props or state) from the component's scope that is used inside the callback. Modern ESLint configurations for React will typically warn you if you miss a dependency, but understanding the underlying reason is critical for debugging.
Applying TypeScript to useCallback
Your preference is to integrate TypeScript throughout, so let's see how it applies here. While the next lesson will dive deeper, we can cover the essentials now.
Often, TypeScript's inference is smart enough to figure out the types for you. However, for event handlers, it's good practice to be explicit.
Learn React Hooks with Typescript
Dave Gray's video 'Learn React Hooks with Typescript' provides a concise look at typing useCallback.
Watch from 08:26 to 12:17. This segment demonstrates how to create a memoized function with useCallback. It shows how to add type definitions for event parameters, such as React.MouseEvent, and how to specify the function's return type (e.g., void).
Here's an example incorporating those ideas:
import React, { useState, useCallback } from 'react';
const MyComponent: React.FC = () => {
const [count, setCount] = useState(0);
// TypeScript can often infer this, but we can be explicit.
// The function takes a mouse event on an HTML button and returns nothing (void).
const handleClick = useCallback((event: React.MouseEvent<HTMLButtonElement>): void => {
// We are using 'count' here, so it MUST be in the dependency array.
console.log(`Button was clicked! Current count is ${count}`);
setCount(c => c + 1); // Functional update is often safer here.
}, [count]); // Add `count` to dependencies.
return <button onClick={handleClick}>Click me</button>;
};
When Should You Use useCallback?
Just like useMemo, useCallback is an optimization with a cost (memory for the memoized function, and CPU to check dependencies). Using it everywhere is a form of premature optimization that can make code harder to read.
The advice is the same: profile first. Use the React DevTools Profiler to find performance bottlenecks.
You should primarily reach for useCallback in these scenarios:
- Passing a callback to a memoized component: This is the main use case we've covered. If a child component is wrapped in
React.memo, any function props passed to it must be memoized withuseCallbackfor the optimization to work. - As a dependency of another hook: If a function is listed in the dependency array of a hook like
useEffect, you should wrap it inuseCallbackto prevent the effect from re-running on every render. - When creating custom hooks: It's good practice to return memoized functions from custom hooks to provide a stable API for the components that use them.
React.memo Optimization Guide for Functional Components
The article from strapi.io reinforces this practical advice.
Skim the sections 'Advanced React.memo Optimization Techniques' and 'Implementing React.memo the Right Way'. Note the emphasis on stabilizing references upstream with useCallback and useMemo as a key practice for making React.memo effective.
Conclusion
Congratulations! You've now completed the trio of fundamental React performance hooks: React.memo, useMemo, and useCallback. You understand not just what they do, but how they work together to prevent unnecessary computation and rendering.
Key Takeaways:
useCallbackmemoizes a function, preserving its referential identity across re-renders.- Its primary use is to pass stable function props to child components wrapped in
React.memo. - It is essentially syntactic sugar for
useMemo:useCallback(fn, deps)is equivalent touseMemo(() => fn, deps). - Crucially, the dependency array must include all reactive values used inside the function to avoid bugs caused by stale closures.
- Like
useMemo, it's an optimization to be used surgically in response to measured performance issues, not as a blanket solution.
Preview of the Next Lesson:
We've touched on TypeScript with useMemo and useCallback, but there's more to explore. In our next lesson, we will do a dedicated deep dive into applying TypeScript to useMemo, useCallback, and another important hook, useRef. You'll learn advanced patterns for creating type-safe and highly optimized components.