useCallback memoizes a function reference until its dependencies change. It is useful when function identity affects rendering or Hook dependencies.
1 Function Identity
function Parent() {
const handleClick = () => console.log("Clicked");
return <Child onClick={handleClick} />;
}
A function created during rendering can have a new reference on another render.
2 Basic useCallback
const handleClick = useCallback(
() => console.log("Clicked"),
[]
);
3 With React.memo
const Child = React.memo(function Child({ onClick }) {
return <button onClick={onClick}>Click</button>;
});
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(
() => console.log("Clicked"),
[]
);
return (
<div>
<button onClick={() =>
setCount(previous => previous + 1)
}>{count}</button>
<Child onClick={handleClick} />
</div>
);
}
4 Function Reference Flow
flowchart TD
A[Parent Renders] --> B[Callback]
B --> C{Dependencies Changed}
C -->|No| D[Reuse Function Reference]
C -->|Yes| E[Create New Function]
D --> F[Child Receives Callback]
E --> F
5 Dependencies
const handleUser = useCallback(
() => console.log(userId),
[userId]
);
6 Functional State Updates
const increase = useCallback(
() => setCount(previous => previous + 1),
[]
);
7 useMemo vs useCallback
| Hook | Memoizes |
|---|---|
| useMemo | A calculated value |
| useCallback | A function reference |
8 When Is It Useful?
- A memoized child receives the callback.
- The callback is a dependency of another Hook.
- Reference stability solves a measured performance issue.
9 Common Mistakes
- Using it for every function.
- Missing dependencies.
- Thinking it makes execution faster.
- Thinking it stops the parent from rendering.
10 Interview Questions
- What is useCallback?
- Why memoize a function?
- How does it work with React.memo?
- What is the difference between useCallback and useMemo?
- When should useCallback not be used?
11 Key Takeaways
- useCallback memoizes a function reference.
- It is about identity, not execution speed.
- Dependencies must match values used by the callback.
Conclusion
useCallback becomes useful when function references matter. Learn JavaScript function identity first; then the purpose of this Hook becomes much easier to understand.