Optimizing Callbacks with useCallback
In React, functions are commonly passed from parent components to child components as props. Whenever a function component renders again, JavaScript creates new function objects for functions defined inside that component. This can matter when a child component is memoized and compares its props.
React provides the useCallback Hook to cache a function definition between renders. When its dependencies remain unchanged, React can return the same function reference. This can help memoized child components avoid rendering because of a changed callback prop.
1. What Is useCallback?
useCallback is a React Hook that lets you cache a function definition between renders. React returns the cached function while the dependencies remain unchanged. When a dependency changes, React can return the function created during the new render.
It is especially useful when passing a callback to a memoized child component. Without a stable callback, the child may receive a new function reference on every parent render and render again even though the function performs the same task.
2. Syntax of useCallback
import { useCallback } from "react";
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []);
The syntax contains three important parts:
- Function: The callback you want to cache.
- Dependency array: The reactive values used by the callback.
- Returned function: The function reference you can pass to a child or event handler.
Understanding the Dependency Array
| Syntax | Meaning |
|---|---|
useCallback(() => doSomething(value), [value]) |
The function reference can be reused while value remains unchanged. |
useCallback(() => doSomething(), []) |
No reactive dependencies are listed. The callback can retain its reference across ordinary re-renders. |
useCallback(() => doSomething()) |
Without a dependency array, the function is not cached across renders. |
3. Understanding Function References
JavaScript functions are values. Two functions can contain identical code but still be different function objects. This matters because React.memo compares props by reference for function values.
const firstFunction = () => {
console.log("Hello");
};
const secondFunction = () => {
console.log("Hello");
};
console.log(firstFunction === secondFunction);
Expected Output
false
Both functions contain the same code, but they are separate function objects and have different references.
Similarly, when a React component creates a callback inside its function body, that callback normally has a new reference after each render. useCallback can preserve the reference when its dependencies have not changed.
4. Example Without useCallback
Consider a parent component with a counter and a memoized child button. The parent creates handleClick on every render. When the counter changes, the new callback reference can cause the memoized child to render again.
import { memo, useState } from "react";
const ActionButton = memo(function ActionButton({ onAction }) {
console.log("ActionButton rendered");
return (
<button onClick={onAction}>
Perform Action
</button>
);
});
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Action performed");
};
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<ActionButton onAction={handleClick} />
</div>
);
}
export default Parent;
Expected Behavior
1. Parent renders.
2. ActionButton renders.
3. Clicking Increase Counter updates the parent's state.
4. Parent renders again and creates a new handleClick function.
5. ActionButton receives a new function prop and can render again.
5. Example With useCallback
Now wrap handleClick in useCallback. Since the callback does not depend on changing reactive values, an empty dependency array is suitable for this example.
import { memo, useCallback, useState } from "react";
const ActionButton = memo(function ActionButton({ onAction }) {
console.log("ActionButton rendered");
return (
<button onClick={onAction}>
Perform Action
</button>
);
});
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Action performed");
}, []);
return (
<div>
<h2>Counter: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase Counter
</button>
<ActionButton onAction={handleClick} />
</div>
);
}
export default Parent;
The counter updates normally. Since handleClick keeps the same reference, ActionButton can skip rendering when its other props remain unchanged.
Clicking Perform Action still calls handleClick and prints "Action performed" in the console.
6. Using useCallback with State
When a callback needs to update state based on its previous value, a functional state update can sometimes avoid including that state variable in the dependency array.
import { useCallback, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const increment = useCallback(() => {
setCount(previousCount => previousCount + 1);
}, []);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={increment}>
Increment
</button>
</div>
);
}
export default Counter;
How It Works
- The initial count is 0.
- The increment callback is created through useCallback.
- The user clicks Increment.
- The functional updater receives the latest previous count.
- React updates the count and renders the component again.
- The increment function reference can remain stable.
7. Understanding Stale Closures
A closure allows a function to access variables from the scope where it was created. If a callback uses a state value but the dependency array omits that value, the callback may continue using the value captured by an earlier render.
import { useCallback, useState } from "react";
function Counter() {
const [count, setCount] = useState(0);
const showCount = useCallback(() => {
console.log(count);
}, []);
return (
<div>
<h2>Count: {count}</h2>
<button onClick={() => setCount(c => c + 1)}>
Increase
</button>
<button onClick={showCount}>
Log Count
</button>
</div>
);
}
export default Counter;
In this example, showCount captures the initial count value. Because count is missing from the dependency array, clicking Log Count can continue printing 0 even after the displayed count changes.
Corrected Example
const showCount = useCallback(() => {
console.log(count);
}, [count]);
Now React can return a callback that uses the current count whenever count changes. Always include reactive values used by a callback unless the code is deliberately structured so those values are not needed from the closure.
8. useCallback vs useMemo
| useCallback | useMemo |
|---|---|
| Caches a function definition. | Caches a calculation result. |
| Useful for stable callback props. | Useful for expensive calculations. |
useCallback(fn, [deps]) |
useMemo(() => calculate(), [deps]) |
| Often useful with React.memo. | Often useful for derived values such as filtered lists. |
9. When Should You Use useCallback?
- When passing callbacks to memoized child components.
- When a callback is a dependency of another Hook.
- When a stable function reference avoids measurable unnecessary work.
- When a callback can be reused while its dependencies remain unchanged.
10. When Should You Avoid useCallback?
- When the function is simple and no optimization benefit is expected.
- When the child is not memoized and a stable reference does not help.
- When adding useCallback makes the code harder to understand without measurable benefit.
- When dependencies change on every render, preventing useful reuse.
11. Common Mistakes
- Forgetting reactive dependencies.
- Using an empty dependency array when the callback reads changing state or props.
- Expecting useCallback to prevent the parent from rendering.
- Using useCallback without a reason to preserve the function reference.
- Assuming a cached function reference makes the function execution itself faster.
- Expecting React.memo to help when other props still change.
12. Practice Tasks
Task 1: Stable Callback
Create a Parent component with a counter and a memoized child button. Observe the child's render behavior before and after using useCallback.
Task 2: Counter with Functional Update
Create an increment function using useCallback and a functional state updater. Check whether the callback can use an empty dependency array.
Task 3: Stale Closure
Create a callback that reads count. First omit count from the dependencies, observe the result, and then correct the dependency array.
Task 4: Parent and Child
Pass a callback to a memoized StudentCard component. Change an unrelated parent state and explain why a stable callback can allow the child to skip rendering.
Task 5: Explain the Difference
Explain useCallback, useMemo, and React.memo with one practical example for each.
Summary
The useCallback Hook caches a function reference between renders while its dependencies remain unchanged. It is useful when stable callbacks help memoized child components avoid unnecessary rendering or when a function is used as a Hook dependency. Correct dependency arrays prevent stale closures, and functional state updates can simplify callbacks that depend on previous state. Unlike useMemo, which caches a calculation result, useCallback caches a function definition. At CIIT Training Institute, practice callback memoization with parent-child components and use it when a measurable performance benefit justifies the added complexity.