⚛️ React.js Intermediate

What are the rules of hooks in React?

Answer

React enforces two rules of hooks that must be followed to ensure hooks work correctly. Rule 1: Only call hooks at the top level. Do not call hooks inside loops, conditions, or nested functions. They must always be called in the same order on every render. React identifies which state belongs to which hook call by the call order — if you conditionally skip a hook, the order changes and React loses track of which state is which. Wrong: if (condition) { const [state, setState] = useState(); }. Rule 2: Only call hooks from React functions. Call hooks from function components or from custom hooks — not from regular JavaScript functions, class components, or outside React. The eslint-plugin-react-hooks package enforces both rules automatically with linting. These rules exist because React relies on the call order of hooks to associate state with the correct hook between renders. Violating them produces cryptic bugs that are hard to debug. If you need conditional logic around a hook, put the condition inside the hook: const [state, setState] = useState(); if (!condition) return null;.