
A Cleaner Way to Write Conditional useEffect in React
If you've built anything in React 18+, you've likely felt the pain of Strict Mode . You add a simple event listener, fire an analytics event, or connect a WebSocket. You boot up your dev server, and— boom —it fires twice. React intentionally mounts your component, unmounts it, and remounts it in development to help you catch bugs like stale closures, missed cleanups, and memory leaks. It's an incredibly useful feature, but it can make your development console extremely noisy and trigger unexpected side-effects. Faced with this, developers often end up doing one of three things: Disable Strict Mode entirely (and lose out on finding actual bugs). Add if (!user || !socket) return guard clauses everywhere. Stuff a useRef(false) flag inside the component to prevent double execution. What if you could keep Strict Mode on, but express your effect timing declaratively? Enter @okyrychenko-dev/react-effect-when . 🛑 The Problem with Manual Guards Let's say you want to connect to a WebSocket, but
Continue reading on Dev.to React
Opens in a new tab




