Rules for Using Hooks in React
Hooks are functions that allow using state and other React features in functional components.
But for React to correctly track and call hooks, you must strictly follow rules for their usage.
Main Rules for Using Hooks
Call Hooks Only at Top Level
You cannot call hooks inside conditions, loops or nested functions.
Bad:
if (someCondition) {
const [count, setCount] = useState(0); // error
}
Good:
const [count, setCount] = useState(0);
if (someCondition) {
// can use count here
}
Why? React relies on hook call order at each render. If you call hook inside condition — order can be violated.
Call Hooks Only in Functional Components or Inside Custom Hooks
You cannot call hooks in regular functions, handlers, conditions outside component.
Cannot:
function doSomething() {
const [val, setVal] = useState(0); // error
}
Can:
function MyComponent() {
const [val, setVal] = useState(0); // correct
return <p>{val}</p>;
}
Or inside custom hook:
function useCustomLogic() {
const [state, setState] = useState(false);
return { state, setState };
}
Hooks Must Be Called in Same Order at Every Render
You cannot change hook order under different conditions. This leads to incorrect value matching
// Bad
if (flag) {
useEffect(() => {}, []); // may break on next render
}
How to Ensure Correct Usage?
eslint-plugin-react-hooks— it helps catch violations.- Don't place hooks inside
if,for,switch,try/catchand any nested functions.
Important:
If you violate hook usage rules, React won't be able to properly track state, effects and other internal data. This will lead to errors and unpredictable behavior.