React › Performance (memo/useMemo)
What is the useCallback hook and how is it different from useMemo?
IntermediateAnswer
useCallback remembers a function itself between renders, so the same function reference is reused instead of creating a brand new one every time. useMemo remembers the result of a calculation instead of a function. Both help avoid unnecessary work, but useCallback is specifically for functions, often used together with React.memo to prevent child components from re rendering unnecessarily.
function ParentComponent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log('Button clicked');
}, []);
return <ChildButton onClick={handleClick} />;
}
const ChildButton = React.memo(({ onClick }) => <button onClick={onClick}>Click</button>);Real-world example A parent component passes the same stable function reference to a memoized child button using useCallback, preventing the child from re rendering every time the parent updates for an unrelated reason.