useCallback with stale dependency
Quick summary
Your useCallback dependency array is missing a variable — the callback captures a stale value and uses it when invoked later.
Why this happens
The dependency array omits a state or prop variable that the callback reads
The callback uses a value from an outer scope that changes but is not listed in the deps array
An empty dependency array is used but the callback reads props or state that change over time
Minimal example
function SearchBar({ query, onSearch }) {
const handleSearch = useCallback(() => {
onSearch(query); // query is stale!
}, [onSearch]); // query missing from deps
return <button onClick={handleSearch}>Search</button>;
}function SearchBar({ query, onSearch }) {
const handleSearch = useCallback(() => {
onSearch(query);
}, [onSearch, query]); // all deps included
return <button onClick={handleSearch}>Search</button>;
}Adding query to the dependency array recreates the callback whenever query changes, ensuring it always reads the current value.
How to diagnose
Log the values inside the callback to check if they reflect the current props and state
Use the exhaustive-deps eslint rule to detect missing dependencies in useCallback
Compare the callback behavior with a non-memoized version to detect staleness
How to fix
Add all variables the callback reads to the dependency array of useCallback
Use functional state updates inside the callback to avoid needing the state value in deps
Remove useCallback if the function is not passed to a memoized child or used as an effect dependency
How to prevent
Always include all variables the callback reads in the dependency array
Use the exhaustive-deps eslint rule and prefer functional updates to minimize dependency tracking
Related Resources
Related Lessons
- useCallback
Learn about callback memoization.