Why useEffect is Wrong for Click Handlers
You'll learn: Why click logic belongs in event handlers, not effects, and how useEffect runs at the wrong time for user interactions.
The Timing Mismatch
useEffect runs after React finishes rendering your component and painting to the screen. It's designed for synchronizing with external systems, not responding to user actions.
When a user clicks a button, they expect immediate feedback. But if you put that logic in a useEffect, here's what happens:
- User clicks
- React re-renders
- React paints to screen
- Then your effect runs
That delay might be milliseconds, but it's architecturally wrong and can cause real problems.
The Right Tool for the Job
Think of it like a restaurant kitchen:
- Event handlers are the line cooks who respond to orders immediately
- Effects are the cleaning crew who work after service ends
You wouldn't ask the cleaning crew to cook the food—they show up at the wrong time!
// ❌ Wrong: Using effect for click logic
function Counter() {
const [count, setCount] = useState(0);
const [clicked, setClicked] = useState(false);
useEffect(() => {
if (clicked) {
console.log('Button was clicked!');
setClicked(false);
}
}, [clicked]);
return <button onClick={() => setClicked(true)}>Click me</button>;
}
// ✅ Right: Handle click directly
function Counter() {
const [count, setCount] = useState(0);
const handleClick = () => {
console.log('Button clicked!');
setCount(count + 1);
};
return <button onClick={handleClick}>Click me</button>;
}
Key Takeaway: Click handlers should run synchronously when the user acts, not asynchronously after render. Use onClick and other event handlers for user interactions—effects are for side effects that synchronize with the render lifecycle, not for responding to events.