Wrapping Callbacks with useCallback for memo Children
What you'll learn: How to use useCallback to create stable function references that prevent unnecessary re-renders in memoized child components.
The Problem with Callbacks and React.memo
You've wrapped a child component in React.memo, expecting it to skip re-renders when props haven't changed. But if you're passing a callback function as a prop, you'll notice the child still re-renders every time the parent does. Why?
Because functions are objects in JavaScript, and every time your parent component renders, it creates a new function instance—even if the function does the exact same thing. React.memo sees a different reference and thinks the prop changed, so it re-renders the child anyway.
The Solution: useCallback
useCallback tells React to "remember" your function between renders. Instead of creating a new function every time, React returns the same function reference until its dependencies change:
function Parent() {
const [count, setCount] = useState(0);
// Without useCallback: new function every render
// const handleClick = () => setCount(c => c + 1);
// With useCallback: stable reference
const handleClick = useCallback(() => {
setCount(c => c + 1);
}, []); // Empty dependencies = never changes
return <MemoizedChild onClick={handleClick} />;
}
const MemoizedChild = React.memo(function Child({ onClick }) {
// Now this only re-renders if onClick reference actually changes
return <button onClick={onClick}>Click me</button>;
});
Why This Matters
Without useCallback, React.memo can't help you. The memo check sees a "new" function prop and renders anyway. With useCallback, the function reference stays the same, the shallow comparison passes, and the child skips rendering.
Key Takeaway: useCallback and React.memo work together—memoize your callbacks so memoized components can actually skip re-renders when parent state changes.