Refactor: Moving Logic into the Handler
You'll learn: How to eliminate unnecessary useEffect calls by putting event-triggered logic directly where it belongs—in the event handler itself.
The Core Idea
When you find yourself using useEffect to watch state that was just set by a button click or form submission, you're creating an extra render cycle for no reason. The fix is simple: perform all the logic directly inside the event handler that triggered the change in the first place.
Think of it like ordering coffee. You don't tell the barista your order, wait for them to write it down, then wait for them to read what they wrote before they start making it. You tell them your order and they immediately start making it—one step, direct action.
Before: The Antipattern
function BadExample() {
const [count, setCount] = useState(0);
useEffect(() => {
// This runs AFTER the render caused by setCount
console.log('Count changed:', count);
// Maybe send analytics, update localStorage, etc.
}, [count]);
function handleClick() {
setCount(count + 1);
}
return <button onClick={handleClick}>Increment</button>;
}
This causes two updates: one to set state, another when the effect runs.
After: Direct Handler Logic
function GoodExample() {
const [count, setCount] = useState(0);
function handleClick() {
const newCount = count + 1;
setCount(newCount);
// Do everything right here
console.log('Count changed:', newCount);
// Send analytics, update localStorage, etc.
}
return <button onClick={handleClick}>Increment</button>;
}
One event, one render, all logic in the right place.
Key Takeaway: If logic should happen because a user clicked something, put that logic in the click handler—not in a useEffect watching the state that click changed.