The Behavior
In React 18+, if you are wrapped in <StrictMode>, components mount, unmount, and remount instantly.
- Mount -> Effect runs.
- Unmount -> Cleanup runs.
- Remount -> Effect runs again.
Why?
React is preparing for a future where components can be unmounted and preserved (Offscreen API). It ensures your effects are resilient to being stopped and started.
How to Handle It?
Do not use a ref to block it. Fix your cleanup function instead.
// ❌ BAD: Trying to "fix" React
const ranOnce = useRef(false);
useEffect(() => {
if (ranOnce.current) return;
ranOnce.current = true;
// ...
}, []);
// ✅ GOOD: Proper cleanup
useEffect(() => {
const connection = connect();
return () => connection.disconnect(); // Handles the unmount perfectly
}, []);
Sponsored Content
Google AdSense Placeholder
CONTENT SLOT