Hooks in Callbacks and Event Handlers
What you'll learn: Why calling hooks inside event handlers or async callbacks breaks React's rules and how to avoid this common mistake.
The Render Phase vs. Event Phase
Hooks must be called during the render phase of your component—when React is evaluating your component function to determine what to display. Event handlers and callbacks like setTimeout, promises, or button clicks happen after rendering is complete, in the event phase.
This is a hard rule: hooks cannot be called inside callbacks or event handlers.
Why This Breaks Everything
Remember that React relies on hooks being called in the same order every render. When you call a hook inside an event handler, it runs outside the render cycle, breaking React's internal tracking system. React won't know which hook call corresponds to which piece of state.
// ❌ WRONG - Hook inside event handler
function BadExample() {
function handleClick() {
const [count, setCount] = useState(0); // NEVER DO THIS
setCount(count + 1);
}
return <button onClick={handleClick}>Click me</button>;
}
// ✅ CORRECT - Hook at top level
function GoodExample() {
const [count, setCount] = useState(0); // Hook during render
function handleClick() {
setCount(count + 1); // Using the setter is fine
}
return <button onClick={handleClick}>Click me</button>;
}
The Rule
Call all hooks at the top level of your component or custom hook. Inside event handlers, you can use the values or setters that hooks return, but you cannot call the hooks themselves.
Key Takeaway: Hooks must run during render, not inside callbacks—call them at the top level and use their return values in your event handlers.