Cleanup in StrictMode: Double Invocation
What you'll learn: How React's StrictMode intentionally runs your effect setup and cleanup twice in development to help you catch missing cleanup bugs early.
Why StrictMode Double-Invokes Effects
In development mode, when your component is wrapped in <React.StrictMode>, React intentionally runs your effect setup, immediately runs cleanup, then runs setup again. This might seem odd, but it's a debugging feature designed to expose problems before they reach production.
The sequence looks like this:
- Component mounts
- Effect runs (setup)
- Effect cleanup runs immediately
- Effect runs again (setup)
What This Reveals
This double invocation surfaces bugs related to missing or incomplete cleanup. If your effect subscribes to something, starts a timer, or adds an event listener, but your cleanup doesn't properly undo it, the double invocation will make the problem obvious in development.
Think of it like a fire drill: you wouldn't wait for a real emergency to discover your fire extinguisher is empty. StrictMode creates a "mini unmount/remount cycle" to ensure your cleanup actually works.
What You'll See
You might notice console logs appearing twice, or timers firing unexpectedly. This is intentional and only happens in development. Production builds run effects normally (setup once on mount, cleanup once on unmount).
If you see doubled behavior, don't remove StrictMode—fix your cleanup! The double invocation is telling you there's a real bug that could cause memory leaks, duplicate subscriptions, or stale event listeners in production when components actually unmount and remount (navigation, conditional rendering, etc.).
Key Takeaway: StrictMode's double setup→cleanup→setup cycle in development is a diagnostic tool that helps you catch missing cleanup logic before it causes production bugs—embrace it, don't fight it.