I have read that the rules for using React's hooks are:
Don’t call Hooks inside loops, conditions, or nested functions. Instead, always use Hooks at the top level of your React function, before any early returns. It’s not supported to call Hooks (functions starting with use) in any other cases, for example:
- 🔴 Do not call Hooks inside conditions or loops.
- 🔴 Do not call Hooks after a conditional return statement.
- 🔴 Do not call Hooks in event handlers.
- 🔴 Do not call Hooks in class components.
- 🔴 Do not call Hooks inside functions passed to useMemo, useReducer, or useEffect.
See rules
Yet React documentation shows an example where they call setCount inside an onClick button function (handleClick). Isn't the function handleClick called by onClick an event handler? And further more doesn't this example violate the rule that it must be called in the top-level? I must be missing something obvious.
How do I create a handleClick using setCount so as to not violate React's hook rules?
Here is the code from the React documentation:
import { useState } from 'react';
export default function Counter() {
const [count, setCount] = useState(0);
function handleClick() {
setCount(count + 1);
}
return (
<button onClick={handleClick}>
You pressed me {count} times
</button>
);
}