Course contentsShow
← React
Lesson 662 of 2,39617. Common useEffect MistakesFree lesson

Refactoring: From Effect to Direct Call

Step-by-step patterns for extracting effect logic into functions that can be called directly from event handlers where appropriate.

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

  1. Identify the logic currently living in your effect
  2. Extract it into a function (often with a handle prefix)
  3. Call that function directly from the event handler
  4. Delete the effect and any state variables that were only triggering it
  5. 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.