react
runtime_error
ai_generated
true
Warning: A stale closure was detected. The callback passed to useCallback references a variable that may be outdated.
ID: react/use-callback-stale-closure
90%Fix Rate
85%Confidence
1Evidence
2023-11-15First Seen
Version Compatibility
| Version | Status | Introduced | Deprecated | Notes |
|---|---|---|---|---|
| React 18.2.0 | active | — | — | — |
| React 19.0.0-rc.1 | active | — | — | — |
Root Cause
The useCallback hook captures a variable in its closure that is not listed in its dependency array, causing the callback to reference a stale value.
generic中文
useCallback 钩子在其闭包中捕获了一个未在依赖数组中列出的变量,导致回调引用了过时的值。
Official Documentation
https://react.dev/reference/react/useCallbackWorkarounds
-
95% success Add the missing variable to the dependency array of useCallback. For example: const handleClick = useCallback(() => { console.log(count); }, [count]);
Add the missing variable to the dependency array of useCallback. For example: const handleClick = useCallback(() => { console.log(count); }, [count]); -
85% success Use a ref to store the variable and access it inside the callback without adding it to dependencies. Example: const countRef = useRef(count); countRef.current = count; const handleClick = useCallback(() => { console.log(countRef.current); }, []);
Use a ref to store the variable and access it inside the callback without adding it to dependencies. Example: const countRef = useRef(count); countRef.current = count; const handleClick = useCallback(() => { console.log(countRef.current); }, []); -
90% success Upgrade to React 19 and use the new use hook which automatically tracks dependencies.
Upgrade to React 19 and use the new use hook which automatically tracks dependencies.
中文步骤
Add the missing variable to the dependency array of useCallback. For example: const handleClick = useCallback(() => { console.log(count); }, [count]);Use a ref to store the variable and access it inside the callback without adding it to dependencies. Example: const countRef = useRef(count); countRef.current = count; const handleClick = useCallback(() => { console.log(countRef.current); }, []);Upgrade to React 19 and use the new use hook which automatically tracks dependencies.
Dead Ends
Common approaches that don't work:
-
70% fail
This ignores the stale closure issue and may still reference outdated values, leading to bugs.
-
80% fail
useMemo is for values, not callbacks, and does not solve the dependency tracking issue.
-
90% fail
This forces the callback to always be stale, breaking any logic that relies on current state.