react runtime_error ai_generated partial

Warning: Component renders twice in development. useEffect cleanup runs immediately after mount. API called twice on component mount.

ID: react/strict-mode-double-invoke-effect

Also available as: JSON · Markdown · 中文
75%Fix Rate
82%Confidence
1Evidence
2023-05-20First Seen

Version Compatibility

VersionStatusIntroducedDeprecatedNotes
[email protected] active
[email protected] active

Root Cause

React StrictMode in development intentionally double-invokes effects to detect side-effect bugs, causing cleanup to run immediately after mount and effects to fire twice.

generic

中文

开发环境中的 React StrictMode 会故意双重调用副作用以检测副作用错误,导致清理在挂载后立即运行,并且副作用触发两次。

Official Documentation

https://react.dev/reference/react/StrictMode

Workarounds

  1. 90% success Ensure useEffect has a proper cleanup function that cancels the API call or subscription. This makes the double invocation harmless.
    Ensure useEffect has a proper cleanup function that cancels the API call or subscription. This makes the double invocation harmless.
  2. 80% success Use useRef to track if the effect has already run and skip the second invocation if needed (only for specific cases like analytics).
    Use useRef to track if the effect has already run and skip the second invocation if needed (only for specific cases like analytics).

中文步骤

  1. Ensure useEffect has a proper cleanup function that cancels the API call or subscription. This makes the double invocation harmless.
  2. Use useRef to track if the effect has already run and skip the second invocation if needed (only for specific cases like analytics).

Dead Ends

Common approaches that don't work:

  1. Removing StrictMode wrapper entirely to stop double invocations 60% fail

    StrictMode is a development tool; removing it hides the bug but doesn't fix it. The same bug may cause issues in production if effects have improper cleanup.

  2. Adding a flag to prevent the second API call (e.g., if (called) return) 75% fail

    This masks the StrictMode behavior but may break cleanup logic or cause stale data if the flag is not reset properly.

  3. Ignoring the double call as a development-only issue 50% fail

    If the effect has side effects like subscriptions or analytics, the double call can cause production-like bugs that are hard to debug.