Rules of Hooks

Last updated: 2026-11-02

Rules of Hooks Rules of Hooks

Hooks obey two iron rules: call them only at the top level of a function component or a custom Hook, never inside a loop, a condition or a nested function; and call them only from React functions, never from plain JavaScript functions. React matches each Hook to its state by call order, so once the order shifts the state gets crossed between slots and the UI updates the wrong value.

GroupRouting & State Mgmt
KindPattern

ℹ️ Info The editor transpiles JSX to JavaScript and renders the real UI in a sandbox; components mount automatically — no manual render call needed.

📝 Syntax

// ✅ Call unconditionally at the top level
function Counter() {
  const [n, setN] = useState(0)
  useEffect(() => { /* ... */ }, [])
  // ❌ Not allowed: if (n > 0) useEffect(...)
  // ❌ Not allowed: useState(0) inside a for loop
  return <button onClick={() => setN(n + 1)}>{n}</button>
}

Returns:No return value; this is a coding pattern rather than a callable API.

▶ Example

The example runs out of the box: it auto-renders when expanded, and edits take effect instantly.

Output:

The panel lists two ✓ rules and one ✗ counter-example; clicking the buttons updates the count and the checkbox, and the Hooks keep running in the same fixed order no matter how you interact, so the state never gets crossed between slots.

💡 Key Points

⚠️ Warning Breaking a rule does not throw right away - you get strange bugs like "clicking button A changes the value of B"; eslint-plugin-react-hooks catches them before the build.
💡 Tip An early return must come after every Hook call, otherwise one render skips a Hook and shuffles the call order.
ℹ️ Info React Compiler can optimize components at build time, but the two rules remain the precondition for it to work.
More case studies coming soon.

📚 Related Tutorials

❓ FAQ

Q Why can a Hook not be called inside a condition?
A React pairs each Hook with its state by call order; a conditional call makes the order drift and the n-th Hook ends up reading somebody else's state.
Q Can a custom Hook call other Hooks?
A Yes, that is exactly what a custom Hook is for - a function whose name starts with use follows the same top-level call rules inside its body.
Q Can a component return before calling its Hooks?
A No. Either move the Hooks above the return, or extract the JSX that comes after the return into a child component, so every Hook runs on every render.
Web-Tutorial.com

Web-Tutorial Tech Team

A team of developers maintaining programming tutorials. Each tutorial is written and reviewed by developers with expertise in that field. We work to keep our content accurate and reliable — if you spot an issue, please let us know.

100%

🙏 帮我们做得更好

我们是刚上线的编程教程站,几个人的小团队,精力有限。页面虽经检查,难免还有疏漏——链接失效、排版错乱、内容有误、语言生硬……

如果您发现了,麻烦告诉我们,我们会在收到反馈后第一时间进行修复,再次感谢您的光临 🙏