Understanding useCallback Hook
Learn how to memoize functions with useCallback to prevent unnecessary re-renders.

What is useCallback?#
useCallback returns a memoized version of the callback that only changes if one of the dependencies has changed. This is useful when passing callbacks to optimized child components.
Basic Syntax#
Code
import { useCallback } from 'react';
const memoizedCallback = useCallback(() => {
doSomething(a, b);
}, [a, b]);Example: Preventing Re-renders#
Code
function Parent() {
const [count, setCount] = useState(0);
const [name, setName] = useState("");
const handleClick = useCallback(() => {
console.log("Button clicked");
}, []); // Empty deps - function never changes
return (
<div>
<input value={name} onChange={(e) => setName(e.target.value)} />
<ExpensiveChild onClick={handleClick} />
</div>
);
}
const ExpensiveChild = React.memo(({ onClick }) => {
console.log("Child rendered");
return <button onClick={onClick}>Click me</button>;
});With Dependencies#
Code
function TodoList({ todos }) {
const [filter, setFilter] = useState("");
const handleToggle = useCallback((id) => {
// Toggle todo logic
setTodos(prev => prev.map(todo =>
todo.id === id ? { ...todo, done: !todo.done } : todo
));
}, []); // No dependencies needed if using functional update
return (
<div>
{todos.map(todo => (
<TodoItem
key={todo.id}
todo={todo}
onToggle={handleToggle}
/>
))}
</div>
);
}When to Use useCallback#
- Passing callbacks to memoized child components
- Callbacks used in other hooks' dependency arrays
- Preventing unnecessary re-renders
Best Practices#
- Don't wrap every function - profile first
- Use with React.memo for child components
- Include all dependencies in the array
- Consider if the optimization is worth the complexity