What is useCallback?
The useCallback hook is a React hook that returns a memoized version of a callback function. It only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components that rely on reference equality to prevent unnecessary renders.
The Problem: Referential Equality
In JavaScript, a function defined inside a component is recreated on every render. Even if the function logic is identical, the memory reference changes. If you pass this function as a prop to a child component wrapped in React.memo, that child will re-render every time because it sees a 'new' prop.
When to Use useCallback
- Passing callbacks to optimized child components (using
React.memo). - When the function is a dependency for other hooks like
useEffect. - Preventing 'Effect' loops: If a function is defined in the body and used in
useEffect, it will trigger the effect on every render unless memoized. - Custom Hooks: When returning functions from custom hooks so consumers can safely use them in their own dependency arrays.
useCallback vs. useMemo
While both hooks are for memoization, they serve different purposes:
| Hook | Returns | Primary Use Case |
|---|---|---|
| useCallback | The function itself (memoized) | Preventing function recreation for props/deps |
| useMemo | The result of a function (memoized value) | Expensive calculations or object/array stability |
Common Mistake: Over-optimization
Don't wrap every function in useCallback. It has its own cost (memory for the dependency array and the hook call itself). If a component is cheap to re-render, or if you aren't passing the function to a React.memo component, the overhead of useCallback might be greater than the benefit.
Best Practices
- Always include all dependencies used inside the function in the dependency array.
- Use functional updates (e.g.,
setCount(c => c + 1)) to reduce the number of dependencies required. - Pair with React.memo:
useCallbackis mostly useless unless the child component receiving the prop is also memoized.