CPCODELAB
React

Rules of Hooks

6 min read

Why Hooks Have Rules

React identifies which hook corresponds to which state by relying on the call order being the same on every render. This is why there are two inviolable rules.

  • Only call hooks at the top level — never inside loops, conditions, or nested functions.
  • Only call hooks from React functions — function components or custom hooks. Never from regular JS functions or class components.
jsx
// WRONG — conditional hook call breaks the call order
function BadComponent({ isLoggedIn }) {
  if (isLoggedIn) {
    const [name, setName] = useState(''); // Error!
  }
}

// CORRECT — call unconditionally, use the value conditionally
function GoodComponent({ isLoggedIn }) {
  const [name, setName] = useState('');
  if (!isLoggedIn) return null;
  return <p>Hello, {name}</p>;
}

Install the eslint-plugin-react-hooks package. It enforces both rules automatically at lint time, catching mistakes before they reach the browser.

Ready to test yourself?
Practice React— quiz & coding exercises