The Event Handler Pattern
What you'll learn: How to handle user actions with event handlers instead of useEffect, keeping your code synchronous and predictable.
The Core Idea
When a user clicks a button, types in a field, or submits a form, your code should respond directly in an event handler—not by setting state and waiting for an effect to react to that state change.
Event handlers run synchronously in response to user actions. They execute immediately when the interaction happens. This is fundamentally different from effects, which run after render as a side effect of state changing.
Why This Matters
Think of event handlers like answering a phone call: when someone calls (user clicks), you pick up immediately (handler runs). You don't wait for the phone to ring (state to change), then check later whether you missed a call (effect runs) to decide what to do.
// ❌ Anti-pattern: Using effect to respond to user action
function SaveButton() {
const [clicked, setClicked] = useState(false);
useEffect(() => {
if (clicked) {
saveData();
setClicked(false);
}
}, [clicked]);
return <button onClick={() => setClicked(true)}>Save</button>;
}
// ✅ Direct event handler pattern
function SaveButton() {
return <button onClick={saveData}>Save</button>;
}
The first approach is overcomplicated: it sets state just to trigger an effect. The second is direct: the user clicks, the handler runs immediately.
Event handlers are for responding to user actions. Effects are for synchronizing with external systems. Don't blur the lines.
Key Takeaway: User interactions should trigger event handlers directly, not state changes that trigger effects—keep cause and effect close together for maintainable, predictable code.