Course contentsShow
← React
Lesson 676 of 2,39618. When NOT to Use useEffectFree lesson

The Common Mistake: Effect Watching State Set by Click

Identifying the antipattern of setting state in onClick and then using useEffect to respond to that state change.

The Common Mistake: Effect Watching State Set by Click

You'll learn: How to spot and avoid the antipattern of setting state in a click handler and then using useEffect to react to that state change.

The Antipattern Explained

Beginners sometimes write code like this:

const [clicked, setClicked] = useState(false);

useEffect(() => {
  if (clicked) {
    console.log('Button was clicked!');
    // Do something...
    setClicked(false);
  }
}, [clicked]);

return <button onClick={() => setClicked(true)}>Click me</button>;

This creates an unnecessary roundabout path: click → state update → re-render → effect runs → more logic.

Why This is Wrong

The click handler already knows the button was clicked. There's no need to store clicked as state and wait for an effect to notice it. You're essentially leaving yourself a note to remember something you already know in the moment.

Think of it like this: Instead of eating your lunch when you're hungry, you write "I'm hungry" on a sticky note, wait for someone else to read it later, and then they tell you to eat. Just eat the lunch directly!

The Correct Pattern

Put the logic directly in the event handler:

const handleClick = () => {
  console.log('Button was clicked!');
  // Do the thing right here
};

return <button onClick={handleClick}>Click me</button>;

No state needed. No effect needed. The action happens immediately when the user clicks.

Key Takeaway: If you're setting state in onClick purely to trigger a useEffect, you're overcomplicating it—just do the work directly in the click handler.