What are the rules of Hooks?

Hooks in React follow a few fundamental rules to ensure they work correctly. These rules are enforced by React's linter plugin (eslint-plugin-react-hooks).

Rules of Hooks
  1. Only Call Hooks at the Top Level
    • Do not call Hooks inside loops, conditions, or nested functions.
    • Always call Hooks at the top level of a functional component or within another Hook.
    • This ensures Hooks run in the same order on every render.
    Incorrect :
    if (someCondition) {
      const [state, setState] = useState(0); //  Hook inside condition
    }
    
    Correct :
    const [state, setState] = useState(0); //  Always at the top level
    if (someCondition) {
      console.log(state);
    }
    
  2. Only Call Hooks from React Functions
    • You can use Hooks inside:
      • React functional components
      • Custom Hooks
    • Do not use Hooks inside:
      • Regular JavaScript functions
      • Class components
    Incorrect :
    function someUtilityFunction() {
      const [count, setCount] = useState(0); //  Hooks inside a regular function
    }
    
    Correct :
    function MyComponent() {
      const [count, setCount] = useState(0); //  Hooks inside a functional component
    }
    
  3. Use Hooks in the Same Order Every Time
    • Hooks rely on the order they are called in.
    • If you put them inside conditions or loops, their order may change between renders, causing unexpected bugs.
  4. Always Use the use Prefix for Custom Hooks
    • If you create a custom Hook, name it with the use prefix (e.g., useMyHook).
    • This helps React detect Hooks and apply its rules.
    Correct :
    function useCustomHook() {
      const [value, setValue] = useState(0);
      return [value, setValue];
    }
    
    Incorrect :
    function customHook() { //  No "use" prefix
      const [value, setValue] = useState(0);
      return [value, setValue];
    }
    

How to Enforce Hook Rules?

React provides an ESLint plugin:

npm install eslint-plugin-react-hooks --save-dev

This will warn you if you break any Hook rules.