The Dependency Array Challenge in useCallback
What you'll learn: Why keeping useCallback dependencies correct becomes tricky when your callback needs frequently-changing values.
The Core Problem
You've wrapped a callback with useCallback to keep it stable for a memoized child component. But what happens when that callback needs to access state or props that change often? Every time you add a dependency to the array, you break the stability you were trying to achieve—the callback gets recreated anyway.
This is the central tension: useCallback only provides stability when dependencies remain constant. If your callback reads from state that updates frequently, you're stuck in a dilemma.
The Scenario
function TodoList({ filter }) {
const [todos, setTodos] = useState([]);
const [count, setCount] = useState(0);
// Problem: count changes often, so this callback recreates often
const handleAdd = useCallback((text) => {
setTodos([...todos, { id: count, text }]);
setCount(count + 1);
}, [todos, count]); // Must include these or get stale values
return <ExpensiveForm onSubmit={handleAdd} />;
}
Every time count or todos changes, handleAdd gets recreated. Your React.memo on ExpensiveForm can't skip re-renders because it receives a new function reference each time.
The Tension
Option 1: Omit dependencies → get stale closures and bugs
Option 2: Include all dependencies → lose stability benefits
You need all the values to work correctly, but including them defeats the purpose of useCallback.
Key Takeaway: The dependency array challenge reveals that useCallback alone isn't enough when your handler depends on frequently-changing state—you need additional patterns like functional updates or useRef to maintain both correctness and stability.