Skip to content

How to Fix React 'Rules of Hooks' Violation Error

DodaTech 2 min read

In this tutorial, you'll learn about How to Fix React 'Rules of Hooks' Violation Error. We cover key concepts, practical examples, and best practices.

The Problem

You see React Hook "useState" is called conditionally. React Hooks must be called in the exact same order in every component render because a hook is placed inside an if statement, loop, or callback. This error is enforced by the ESLint plugin and by React's runtime.

Quick Fix

Move Hooks to the Top Level of the Component

node -e "
// ❌ Wrong: hook inside condition
function BadComponent({ visible }) {
    if (visible) {
        const [count, setCount] = React.useState(0);
    }
}

// ✅ Correct: hook at top level
function GoodComponent({ visible }) {
    const [count, setCount] = React.useState(0);
    return visible ? <p>{count}</p> : null;
}
console.log('Hooks moved to top level');
"
# Hooks moved to top level

Call hooks unconditionally at the top of your function component. Conditional values should be handled in the JSX return, not around the hook calls themselves.

Do Not Call Hooks Inside Loops

node -e "
// ❌ Wrong: hook inside loop
function BadList({ items }) {
    for (const item of items) {
        const [selected, setSelected] = React.useState(false);
    }
}

// ✅ Correct: single state for the component
function GoodList({ items }) {
    const [selectedIndex, setSelectedIndex] = React.useState(null);
    return items.map((item, i) => (
        <div key={i} onClick={() => setSelectedIndex(i)}>{item}</div>
    ));
}
console.log('Hooks extracted from loop');
"
# Hooks extracted from loop

If you need per-item state, either lift state to the parent component or create a separate child component that holds its own state and render it inside the loop.

Extract Nested Hooks into Separate Components

node -e "
// ❌ Wrong: hooks inside an event handler
function BadForm() {
    const handleClick = () => {
        const [error, setError] = React.useState(null);
    };
}

// ✅ Correct: hook at top level
function GoodForm() {
    const [error, setError] = React.useState(null);
    const handleClick = () => setError(null);
    return <button onClick={handleClick}>Clear</button>;
}
console.log('Hooks extracted from callback');
"
# Hooks extracted from callback

Event handlers and callbacks cannot contain hooks. Move state declarations to the component body and use the setter function inside the callback.

Additional Troubleshooting

# Check the error message and stack trace for more context
echo "Review the full error output to identify the root cause"

If the above steps do not resolve the issue, examine the complete error message and stack trace. Often the key detail is in the middle of the traceback rather than the final line. Search for the error message in the project documentation or issue tracker for additional solutions.

Prevention

  • Always call hooks at the top level of a React function component or a custom hook
  • Never wrap useState, useEffect, useContext, or any other hook inside if, for, while, or nested functions
  • Use the ESLint plugin eslint-plugin-react-hooks with the rules-of-hooks rule enabled in your linter config
  • Extract complex logic into custom hooks that themselves follow the rules of hooks at their top level

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro