StrictMode effect double-invocation limits for external resource management
20K reputation · 09 Dec 2024, 10:05 UTC
Resource Leak Detection in Development
React's <StrictMode> intentionally double-invokes useEffect setup and cleanup functions in development builds. This behavior is designed to ensure that components are resilient to remounting and that cleanup logic correctly releases resources such as WebSocket connections, timers, or event subscriptions.
Integration with External Systems
When effects interact with non-React systems—such as incrementing a server-side counter or initializing a third-party library—the double-invocation can lead to duplicate side effects if the logic is not idempotent or lacks a corresponding cleanup function. While production builds execute these effects once per mount, the development behavior surfaces leaks that may otherwise only appear during navigation or when using Suspense boundaries.
There is often uncertainty regarding the strategy for handling legacy subtrees where strict cleanup is not currently implemented but removing <StrictMode> would mask potential production bugs.
- Does a failure to handle double-invocation in development necessarily indicate a production bug in all remount scenarios?
- What are the recommended criteria for deciding between refactoring legacy effects for idempotency versus scoping
<StrictMode>to specific component branches?