Back to results for “Custom Hooks”
React › Custom Hooks

What are the rules you must follow when writing and using hooks, including custom hooks?

Intermediate

Answer

Hooks must always be called at the top level of a function component or another hook, never inside loops, conditions, or nested functions. This ensures React can correctly keep track of each hook's state between renders. Following this rule keeps custom hooks working reliably and predictably.
// Wrong, hook called conditionally
if (isLoggedIn) {
  useEffect(() => { /* ... */ }, []);
}

// Correct, hook always called, condition handled inside
useEffect(() => {
  if (isLoggedIn) { /* ... */ }
}, [isLoggedIn]);
Real-world example A developer fixes a confusing bug where a component's state seemed to mix up between renders, after discovering a hook was accidentally being called only under a certain condition instead of every single render.

Common follow-ups: Why does breaking this rule cause React to get confused about which state belongs to which hook?;What eslint plugin helps catch these mistakes automatically?