What are React hooks rules and why do they exist?

MediumTechnical
GoogleFrontend Engineer
212

Explain the rules of hooks in React. Why can't we call hooks inside loops, conditions, or nested functions?

1 Answer

178
Top Answer

The Two Rules of Hooks

1. Only call hooks at the top level

Don't call hooks inside loops, conditions, or nested functions.

// ❌ BAD
if (condition) {
  const [state, setState] = useState(0);
}

// ✅ GOOD
const [state, setState] = useState(0);
if (condition) {
  // use state here
}

2. Only call hooks from React functions

Only call hooks from React function components or custom hooks.

Why These Rules Exist

React relies on the order hooks are called to match state with the correct hook. If hooks are called conditionally, the order can change between renders:

// First render:  useState(0), useState('')
// Second render: useState('')  ← Wrong state!

React stores hook state in a linked list. Each hook "claims" the next slot. If order changes, hooks get wrong values.

ESLint Plugin

Use eslint-plugin-react-hooks to catch violations automatically.

HooksExpert

Share Your Answer

Help others by sharing your knowledge and experience with this question.

Coming soon...

Related Questions

View all

More from Google

View all