Loading...
Loading...
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.
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.
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 };
}
You cannot change hook order under different conditions. This leads to incorrect value matching
// Bad
if (flag) {
useEffect(() => {}, []); // may break on next render
}
eslint-plugin-react-hooks — it helps catch violations.if, for, switch, try/catch and 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.