Effects vs Event Handlers
What you'll learn: You'll understand when to use an effect versus when to use an event handler — one of the most important distinctions in React.
The Core Difference
Event handlers respond to specific user interactions — clicks, form submissions, key presses. They run because the user did something.
Effects respond to rendering — they run because the component appeared or updated. They react to the fact that your component is now on screen with certain props or state values.
When to Use Event Handlers
Use event handlers when you want something to happen in response to a user action:
- Submitting a form
- Clicking a button
- Typing in an input
- Hovering over an element
These are cause and effect — the user causes it, your code effects the change.
When to Use Effects
Use effects when you want something to happen because your component rendered with certain data:
- Fetching data when a component mounts
- Subscribing to a service when an ID changes
- Updating the document title to reflect current state
- Logging analytics when a page appears
These are synchronization tasks — keeping something in sync with React's state.
The Key Question
Ask yourself: "Does this need to happen because the user clicked/typed, or because the component is now showing X data?"
If it's the former → event handler
If it's the latter → effect
Example Distinction
- Saving a form when the user clicks "Save" → event handler
- Auto-saving whenever the form data changes → effect
Key Takeaway: Event handlers run because users act; effects run because components render. Choose based on what triggers the need for your side effect.