Course contentsShow
← React
Lesson 1029 of 2,39626. Rules of Hooks Deep DiveFree lesson

Calling Hooks in Event Handlers

Why you can't call useState or useEffect inside onClick or other event callback functions.

Calling Hooks in Event Handlers

You'll learn why calling useState, useEffect, or other Hooks inside event handlers like onClick violates React's rules.

The Core Problem

Event handlers execute after the component has already rendered. React's Hooks must run during the render phase itself, in the same order, every time. When you try to call a Hook inside an event handler, you're attempting to register state or effects outside the render cycle—React's internal Hook registry has already been built for that render, and your late Hook call disrupts the entire order-based system.

Think of it like a roll call: React takes attendance (builds the Hook list) at the start of class (render). If someone tries to add their name to the attendance sheet after roll call is finished (during an event), the seating chart becomes nonsense.

What Happens

// ❌ WRONG: Hook called in event handler
function BadCounter() {
  const handleClick = () => {
    const [count, setCount] = useState(0); // Breaks everything!
    setCount(count + 1);
  };

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

This code will throw an error immediately. React expects all Hooks to be called during the component's render phase, not during event handling.

The Right Way

Call Hooks at the top level of your component, then use their results in event handlers:

// ✅ CORRECT: Hook at top level, used in handler
function GoodCounter() {
  const [count, setCount] = useState(0);

  const handleClick = () => {
    setCount(count + 1); // Just calling the setter
  };

  return <button onClick={handleClick}>Count: {count}</button>;
}

Key Takeaway: Hooks must be called during render at the component's top level—never inside callbacks, event handlers, or after conditional logic. Event handlers use the values and setters that Hooks provide, but cannot call Hooks themselves.