Moving onClick Logic Out of Effects
What you'll learn: How to fix code that incorrectly routes button click logic through useEffect instead of calling functions directly.
The Antipattern
Sometimes developers accidentally create a chain reaction: button click → update state → useEffect sees state change → runs side effect. This adds unnecessary complexity and a render delay.
// ❌ Wrong: routing through useEffect
function SaveButton({ data }) {
const [shouldSave, setShouldSave] = useState(false);
useEffect(() => {
if (shouldSave) {
saveToAPI(data);
setShouldSave(false);
}
}, [shouldSave, data]);
return <button onClick={() => setShouldSave(true)}>Save</button>;
}
The button doesn't need to communicate with the Effect — it can just do the work directly!
The Fix: Call Functions Directly
Effects are for synchronizing with external systems (like subscriptions, browser APIs). Button clicks are events — they should run event handlers immediately.
// ✅ Correct: direct event handler
function SaveButton({ data }) {
const handleClick = () => {
saveToAPI(data);
};
return <button onClick={handleClick}>Save</button>;
}
No state flag. No useEffect. No extra render. The save happens instantly when the user clicks.
Why This Matters
The Effect version causes:
- An extra render cycle (set state → re-render → Effect runs)
- Harder debugging (action is disconnected from cause)
- Confusion about what Effects are for
Key Takeaway: Button clicks and user events should call functions directly — save useEffect for synchronizing with systems that exist outside React's render cycle, not for responding to intentional user actions.