Hook rules in React
In React, Hooks have strict rules you must follow to ensure components behave consistently and predictably. These rules help React track the state and lifecycle of each component properly.
π§ The Two Main Rules of Hooks
β Rule #1: Only Call Hooks at the Top Level
- Never call Hooks inside loops, conditions, or nested functions.
- Always call them at the top level of your component or custom Hook.
Why?
React relies on the order of Hook calls between renders. Calling them conditionally would break the order, causing bugs.
π§± Example β β Correct:
function MyComponent() {
const [count, setCount] = useState(0); // β
OK
useEffect(() => {
// β
OK
}, []);
}
β Wrong:
function MyComponent({ isVisible }) {
if (isVisible) {
const [count, setCount] = useState(0); // β Don't do this!
}
}
β Rule #2: Only Call Hooks from React Functions
You can only call Hooks from:
- Function components
- Custom Hooks
β Donβt call Hooks from:
- Regular JavaScript functions
- Class components
- Event handlers or callbacks (directly)
π§± Example β β Correct:
function useCustomHook() {
const [value, setValue] = useState(0);
}
function MyComponent() {
useCustomHook(); // β
OK
}
β Wrong:
function doSomething() {
useState(0); // β Don't call here
}
π§ͺ Bonus: ESLint Plugin for Enforcing Rules
React provides an official ESLint plugin:
npm install eslint-plugin-react-hooks --save-dev
In your ESLint config:
{
"plugins": ["react-hooks"],
"rules": {
"react-hooks/rules-of-hooks": "error", // β
Enforce Rules
"react-hooks/exhaustive-deps": "warn" // β
Check dependencies in useEffect
}
}
π Summary
Rule | Description |
---|---|
π§ Call Hooks only at top level | Donβt call inside loops, conditions, or nested blocks |
π Call Hooks only in React functions | Use inside function components or custom hooks only |
π‘ Use ESLint plugin | Helps you catch rule violations early |
Comments are closed.