useCallback for Stable Function References
What you'll learn: How to use useCallback to keep the same function reference across renders, preventing unnecessary re-renders in optimized components.
The Core Problem
Every time your component re-renders, any function you define inside it gets recreated as a new reference. JavaScript treats these as different functions, even if they do the exact same thing. This becomes a problem when:
- You pass that function to a memoized child component (
React.memo) - You use that function as a dependency in
useEffect,useMemo, or another hook
The new reference triggers re-renders or effect re-runs, defeating your optimizations.
Enter useCallback
useCallback returns a memoized version of your function that only changes when its dependencies change:
const memoizedCallback = useCallback(
(arg) => {
// Your function logic
doSomething(arg, dependency);
},
[dependency] // Only recreate if 'dependency' changes
);
When This Matters
With memoized children:
const MemoizedChild = React.memo(ExpensiveChild);
function Parent() {
const handleClick = useCallback(() => {
console.log('clicked');
}, []); // Stable reference
return <MemoizedChild onClick={handleClick} />;
// Child won't re-render unnecessarily
}
As effect dependencies:
const fetchData = useCallback(() => {
// fetch logic
}, [userId]);
useEffect(() => {
fetchData();
}, [fetchData]); // Won't re-run unless userId changes
Think of It Like This
Without useCallback, you're creating a new name tag for the same job description every render. useCallback lets you reuse the same name tag until the job actually changes.
Key Takeaway: Use useCallback to maintain stable function references across renders, preventing unnecessary re-renders in memoized children and avoiding unwanted effect re-executions.