Functional Updates to Reduce Dependencies
What You'll Learn
You'll discover how to use setState's functional form to eliminate state dependencies from useCallback, making your memoized callbacks simpler and more stable.
The Dependency Problem
When you wrap a callback with useCallback and that callback updates state based on the current state value, you typically need to include that state in the dependency array:
const increment = useCallback(() => {
setCount(count + 1); // References 'count'
}, [count]); // Must include count
Every time count changes, useCallback creates a new function reference. If you pass this to a React.memo'd child component, the memoization fails because the callback keeps changing.
The Functional Update Solution
React's setState accepts a function that receives the current state as an argument. This eliminates the need to reference the state variable directly:
const increment = useCallback(() => {
setCount(prevCount => prevCount + 1); // No external reference
}, []); // Empty array! Fully stable
Now increment never changes because it doesn't depend on count. The function is created once and reused forever.
Why This Matters for memo
When passing callbacks to memoized children, stable references are crucial:
const ExpensiveChild = React.memo(({ onIncrement }) => {
// Heavy rendering logic
});
// Without functional update: onIncrement changes every render
// With functional update: onIncrement stays the same forever
Breaking Dependency Chains
This pattern breaks cascading dependency chains. Instead of count → increment → child props all updating together, only count changes while increment stays stable.
Key Takeaway: Use the functional form setState(prev => ...) inside useCallback to eliminate state dependencies, creating perfectly stable callbacks that maximize the effectiveness of React.memo on child components.