Skip to content
following-the-rules-of-hooks logo

Rules of Hooks

following-the-rules-of-hooks

Fix React Rules of Hooks violations - conditional calls, hooks in loops/callbacks/classes

SKILL.md

Full skill instructions

Rules of Hooks

React enforces two invariants on Hook usage. Violating these causes state corruption and unpredictable behavior.

The Rules

  1. Top-level only - Never call Hooks inside loops, conditions, nested functions, or try/​catch/​finally
  2. React functions only - Call Hooks exclusively from function components or custom Hooks

Why: Consistent call order across renders; conditional/​dynamic invocation breaks state tracking.

Valid Hook Locations

✅ Top level of function components ✅ Top level of custom Hooks (use* functions)

function Counter() {
  const [count, setCount] = useState(0);
  return <div>{count}</​div>;
}

function useWindowWidth() {
  const [width, setWidth] = useState(window.innerWidth);
  return width;
}

Common Violations

ViolationWhy InvalidFix
Inside if/​elseSkipped on some rendersMove to top; use conditional rendering
Inside loopsVariable call countMove to top; manage array state
After early returnUnreachable on some pathsMove Hook before return
In event handlersCalled outside renderMove to top; use state from closure
In class componentsClasses don't support HooksConvert to function component
Inside callbacksNested function contextMove Hook to top level

Common Fixes

Conditional Hooks

❌ Wrong:

function Profile({ userId }) {
  if (userId) {
    const user = useUser(userId);
  }
}

✅ Right:

function Profile({ userId }) {
  const user = useUser(userId);
  if (!userId) return null;
  return <div>{user.name}</​div>;
}

Pattern: Always call Hook, use conditional rendering for output.

Hooks in Loops

❌ Wrong:

function List({ items }) {
  return items.map(item => {
    const [selected, setSelected] = useState(false);
    return <Item selected={selected} />;
  });
}

✅ Right:

function List({ items }) {
  const [selected, setSelected] = useState({});
  return items.map(item => (
    <Item
      key={item.id}
      selected={selected[item.id]}
      onToggle={() => setSelected(s => ({...s, [item.id]: !s[item.id]}))}
    />
  ));
}

Pattern: Single Hook managing collection, not per-item Hooks.

Hooks in Event Handlers

❌ Wrong:

function Form() {
  function handleSubmit() {
    const [loading, setLoading] = useState(false);
    setLoading(true);
  }
  return <button onClick={handleSubmit}>Submit</​button>;
}

✅ Right:

function Form() {
  const [loading, setLoading] = useState(false);
  function handleSubmit() {
    setLoading(true);
  }
  return <button onClick={handleSubmit} disabled={loading}>Submit</​button>;
}

Pattern: Hook at component level, setter in handler.

Hooks in Classes

❌ Wrong:

function BadCounter() {
  const [count, setCount] = useState(0);
  return <div>{count}</​div>;
}

✅ Right:

function Counter() {
  const [count, setCount] = useState(0);
  return <div>{count}</​div>;
}

Pattern: Use function components for Hooks.

Hooks in Callbacks

❌ Wrong:

function Theme() {
  const style = useMemo(() => {
    const theme = useContext(ThemeContext);
    return createStyle(theme);
  }, []);
}

✅ Right:

function Theme() {
  const theme = useContext(ThemeContext);
  const style = useMemo(() => createStyle(theme), [theme]);
}

Pattern: Call Hook at top level, reference in callback.

Hooks After Early Returns

❌ Wrong:

function User({ userId }) {
  if (!userId) return null;
  const user = useUser(userId);
  return <div>{user.name}</​div>;
}

✅ Right:

function User({ userId }) {
  const user = useUser(userId || null);
  if (!userId) return null;
  return <div>{user.name}</​div>;
}

Pattern: Call all Hooks before any returns.

Custom Hooks

Custom Hooks may call other Hooks because they execute during render phase:

function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}

Requirements: Name starts with use; called from function component or another custom Hook; follows same Rules of Hooks.

Quick Diagnostic

ESLint error: "React Hook cannot be called..."

  1. Check location: Is Hook inside if/​loop/​try/​handler/​class?
  2. Move Hook to top level of component/​custom Hook
  3. Keep conditional logic, move Hook call outside it
  4. Use conditional rendering, not conditional Hooks

Reference: https://react.dev/reference/rules/rules-of-hooks

More skills from majiayu000

xiaohongshu logo
majiayu000/claude-arsenal

xiaohongshu

xiaohongshu

286 148
View
agent-task-conductor logo
majiayu000/claude-skill-registry

agent-task-conductor

Conduct multi-agent task orchestration and workflow coordination.

663 1
View
conductor-setup logo
majiayu000/claude-skill-registry

conductor-setup

Initialize project with Conductor artifacts (product definition,

663 1
View
animation-designer logo
majiayu000/claude-skill-registry

animation-designer

Expert in web animations, transitions, and motion design using Framer Motion and CSS

663 1
View
diagramming logo
majiayu000/claude-skill-registry

diagramming

Creates Mermaid and ASCII diagrams for flowcharts, architecture, ERDs, state machines, mindmaps, and more. Use when user mentions diagram, flowchart, mermaid, ASCII diagram, text diagram, terminal diagram, visualize, C4, mindmap, architecture diagram, sequence diagram, ERD, or needs visual docume...

663 1
View
h3-pg logo
majiayu000/claude-skill-registry-data

h3-pg

PostgreSQL bindings for H3 hexagonal grid system. Use when working with H3 cells in Postgres, including spatial indexing, geometry/geography integration, and raster analysis.

23 1
View
conductor-development logo
majiayu000/claude-skill-registry

conductor-development

Context-Driven Development skill for projects using Conductor. Use this skill when you detect a `conductor/` directory in the project, when working on tasks defined in a `plan.md` file, or when the user asks about tracks, specs, or plans. Automatically applies TDD workflow, tracks task completion...

663 1
View
conductor-status logo
majiayu000/claude-skill-registry

conductor-status

Display project status, active tracks, and next actions

663 1
View
dockerization logo
majiayu000/claude-skill-registry

dockerization

Official Stakpak application containerization standard operating procedure, a step-by-step guidline to properly dockerize applications. This is a rule book curated by the Stakpak Team.

663 1
View

Popular AI tools

Kaiber logo
Video

Kaiber

Generate, edit, and beat-sync AI video with leading models in one workspace.

Paid
View
Vimcal logo
Productivity

Vimcal

The world's fastest calendar for remote work

Free
View

Transform Your Design with AI Designer by ImgCreator.ai

Freemium
View
Akool AI logo
Content & writing

Akool AI

Revolutionizing Video Production with AI-Powered Creativity

Paid
View

Extend an image past the frame and let AI fill the new aspect ratio.

Freemium
View
StarByFace logo
Security

StarByFace

Discover your celebrity doppelgänger with StarByFace!

Free
View
C

ChainClarity explains 700+ crypto whitepapers in plain English, with layered summaries, comparisons, research tools, alerts, and a $4.99 Pro plan.

Freemium
View
Opus Clip logo
Coding & apps

Opus Clip

Opus.ai: Revolutionize Your Web Experience

Free
View