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

Also available as: JSON · Markdown · 中文
90%Fix Rate
85%Confidence
1Evidence
2023-11-15First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
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/useCallback

Workarounds

  1. 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]);
  2. 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); }, []);
  3. 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.

中文步骤

  1. Add the missing variable to the dependency array of useCallback. For example: const handleClick = useCallback(() => { console.log(count); }, [count]);
  2. 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); }, []);
  3. Upgrade to React 19 and use the new use hook which automatically tracks dependencies.

Dead Ends

Common approaches that don't work:

  1. 70% fail

    This ignores the stale closure issue and may still reference outdated values, leading to bugs.

  2. 80% fail

    useMemo is for values, not callbacks, and does not solve the dependency tracking issue.

  3. 90% fail

    This forces the callback to always be stale, breaking any logic that relies on current state.