React ยท Chapter 18 of 42
useCallback Hook
`useCallback` memoizes a function definition itself, returning the same function reference between renders unless dependencies change.
This is useful when passing callbacks to memoized child components (via `React.memo`) to prevent unnecessary re-renders.
Function identity
Normally, a new function is created on every render. useCallback keeps the same reference across renders when dependencies are unchanged.
Pairing with memo
useCallback is most useful when passed to a child wrapped in `React.memo`, since a stable function prevents the child from re-rendering unnecessarily.
Example 1 (jsx)
import { useCallback, useState } from "react";
function Parent() {
const [count, setCount] = useState(0);
const handleClick = useCallback(() => {
console.log("Clicked!");
}, []);
return (
<div>
<button onClick={() => setCount(count + 1)}>Count: {count}</button>
<Child onClick={handleClick} />
</div>
);
}Output
Clicked! (logged only on button press, Child does not re-render needlessly)handleClick keeps the same reference across renders.
Key points
- useCallback memoizes a function reference between renders.
- Useful when passing callbacks to React.memo-wrapped children.
- Without it, a new function is created on every render.
- Overusing it without memoized children provides little benefit.
๐ก Note: useCallback(fn, deps) is equivalent to useMemo(() => fn, deps).
