How useCallback Works and Why is it Needed
useCallback is a React hook that allows memoizing (remembering) a function between component renders.
It returns same version of function if dependencies haven't changed, and prevents creating new function at each render.
Why useCallback?
In JavaScript functions are reference objects. Each time component renders, new function is created:
const handleClick = () => console.log("clicked"); // new function every render
If you pass this function to child component, it will re-render, even if nothing actually changed.
The useCallback hook is needed to avoid this problem:
const handleClick = useCallback(() => {
console.log("clicked");
}, []);
Now handleClick will have same reference, until dependencies in array change.
Syntax
const memoizedCallback = useCallback(() => {
// function
}, [dependencies]);
-
() => {}— function we want to memoize -
[dependencies]— dependencies array, like in useEffect
Example: without useCallback
function Parent() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log("Clicked");
};
return (
<>
<Child onClick={handleClick} />
<button onClick={() => setCount(count + 1)}>+1</button>
</>
);
}
const Child = React.memo(({ onClick }) => {
console.log("🔁 Child rerendered");
return <button onClick={onClick}>Click me</button>;
});
Even when count changes, Child re-renders because handleClick is new reference.
Example: with useCallback
const handleClick = useCallback(() => {
console.log("Clicked");
}, []);
Now Child doesn't re-render because onClick doesn't change.
When to Use useCallback
Use if:
- You pass function to
React.memo-component - Function is used in dependencies of other hooks (
useEffect,useMemo)
Don't need useCallback:
- On every handler "just in case"
- In simple components where re-renders aren't critical
useCallback vs useMemo
| useCallback | useMemo | |
|---|---|---|
| What returns | Returns function | Returns value |
| Example | () => | heavyComputation() |
| Application | Used for handlers | Used for values |
Tip:
useCallback is an optimization tool, not mandatory. Use it when there's specific need to control function references.