Events vs Effects: The Fundamental Distinction
What you'll learn: How to decide whether code belongs in an event handler or a useEffect, the most fundamental question in React side-effect management.
The Core Difference
An event is code that runs because the user did something specific. A click, a form submission, a button press—these are discrete actions that trigger responses.
An effect is code that runs because something changed and needs to stay synchronized. It's about keeping your component in sync with the outside world—WebSocket connections, document titles, localStorage, timers.
The Decision Rule
Ask yourself: "Does this code respond to a specific user action, or does it keep something in sync?"
- User clicked 'Submit'? → Event handler
- Component needs to connect to WebSocket when
roomIdchanges? → Effect - User typed in search box? → Event handler
- Document title needs to reflect current
pageTitlestate? → Effect
Why It Matters
Putting event logic in effects causes bugs. You'll end up with code that runs at the wrong times—on mount, on every render, when unrelated state changes. You'll add awkward dependency arrays trying to prevent it.
Event handlers run once per action. Effects run whenever dependencies change. Mix them up and you fight React instead of working with it.
The Analogy
Event handlers are like doorbells—they ring when someone presses them. Effects are like thermostats—they constantly monitor temperature and adjust when it drifts.
Key Takeaway: If code responds to a specific user action, it belongs in an event handler. If code synchronizes with external systems or props/state changes, it belongs in useEffect.