Refactoring: From Effect to Direct Call
You'll learn: How to extract effect logic into standalone functions that can be called directly from event handlers, eliminating unnecessary effects.
The Core Pattern
When you've identified an effect that's really handling user events (the 'Handle Event in Effect' antipattern), the refactoring path is straightforward: extract the logic into a regular function, then call it directly from your event handler.
Before you had:
// ❌ Effect disguised as event handler
useEffect(() => {
if (shouldSubmit) {
submitForm();
}
}, [shouldSubmit]);
After refactoring:
// ✅ Direct function call from event
function handleSubmit() {
submitForm();
}
<button onClick={handleSubmit}>Submit</button>
Step-by-Step Refactoring
- Identify the logic currently living in your effect
- Extract it into a function (often with a
handleprefix) - Call that function directly from the event handler
- Delete the effect and any state variables that were only triggering it
- Remove now-unused dependencies from your component
The Key Benefit
This isn't just cleaner code—it's more predictable. The logic runs exactly when the user acts, not "after a render when a dependency changes." You eliminate the derived trigger pattern entirely.
Think of it like changing from sending yourself a reminder email to just doing the task immediately when you think of it.
Key Takeaway: When effect logic is really event logic in disguise, extract it into a function and call it directly from the event handler—simpler, faster, and more maintainable.