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

The 'Handle Event in Effect' Antipattern

Recognizing when useEffect is being misused to respond to clicks, form submissions, or other user interactions that belong in event handlers.

The 'Handle Event in Effect' Antipattern

What you'll learn: How to recognize when you're wrongly using useEffect to respond to user interactions instead of event handlers.


The Core Mistake

One of the most common useEffect mistakes is using it to respond to user actions like clicks, form submissions, or keyboard input. You might see code like this:

function BadExample() {
  const [shouldSubmit, setShouldSubmit] = useState(false);

  useEffect(() => {
    if (shouldSubmit) {
      // Submit form logic here
      setShouldSubmit(false);
    }
  }, [shouldSubmit]);

  return <button onClick={() => setShouldSubmit(true)}>Submit</button>;
}

This creates an unnecessary state variable and effect just to do something a plain event handler should do.

Why This Happens

Beginners often think: "I need something to happen after the button click... effects happen after rendering... so I'll use useEffect!" But that's mixing up when effects run (after paint) with what they're for (synchronizing with external systems).

The Right Way

User interactions belong in event handlers, not effects:

function GoodExample() {
  const handleSubmit = () => {
    // Submit form logic here
  };

  return <button onClick={handleSubmit}>Submit</button>;
}

Direct, immediate, and no extra state needed.

The Mental Model

Think of effects like automatic background workers that keep your component in sync with outside systems (WebSocket connections, browser APIs, subscriptions). Event handlers are like direct responses to user commands. Don't hire a background worker to do a job the user just asked for directly!

Key Takeaway: If you're adding state solely to trigger an effect in response to a user action (click, submit, input), you're misusing useEffect. Handle the event directly in an event handler instead.