Skip to content

How to Fix React Hooks Rules Violation

DodaTech Updated 2026-06-24 3 min read

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

The Problem

React throws React Hook "useX" is called conditionally. React Hooks must be called in the exact same order or Invalid hook call when hooks are used inside conditions, loops, or non-component functions.

Quick Fix

Step 1: Do not call hooks inside conditions

Hooks must be called unconditionally at the top level:

function User({ name }) {
    if (name) {
        const [greeting, setGreeting] = useState('Hello');
    }
    return <div>{greeting}</div>;
}

Move hooks outside conditions:

function User({ name }) {
    const [greeting, setGreeting] = useState('Hello');
    if (name) {
        setGreeting('Hi ' + name);
    }
    return <div>{greeting}</div>;
}

Step 2: Do not call hooks inside loops

Calling hooks inside a loop violates the order rule:

function Items({ list }) {
    for (const item of list) {
        const [selected, setSelected] = useState(false);
    }
}

Move the hook call outside the loop and use state arrays:

function Items({ list }) {
    const [selected, setSelected] = useState({});
    return list.map(item => (
        <div key={item.id} onClick={() => setSelected({...selected, [item.id]: true})}>
            {item.name}
        </div>
    ));
}

Step 3: Do not call hooks inside nested functions

Hooks must be in the component body, not inside callbacks:

function Form() {
    const handleSubmit = () => {
        const [error, setError] = useState(null);
    };
}

Move the hook to the component body:

function Form() {
    const [error, setError] = useState(null);
    const handleSubmit = () => {
        setError('Invalid input');
    };
}

Step 4: Only call hooks from React function components or custom hooks

Calling hooks from a regular function throws:

function formatData(data) {
    const [result, setResult] = useState(data);
    return result;
}

Use a custom hook or pass state as a parameter:

function useFormatData(data) {
    const [result, setResult] = useState(data);
    return result;
}

function formatData(data) {
    return data.toUpperCase();
}

Prevention

  • Install and enable the eslint-plugin-react-hooks plugin.
  • Run npx eslint . to automatically detect violations.
  • Keep hooks at the top of the component before any early returns.
  • Use custom hooks to extract complex hook logic.
  • Follow the rule: hooks must be called in the same order on every render.

Common Mistakes with hook rules

  1. Misunderstanding that String is [Char] with poor performance for large text operations
  2. Using foldl instead of foldl' causing stack overflow on large lists
  3. Forgetting deriving (Show, Eq) on custom data types needed for debugging

These mistakes appear frequently in real-world REACT code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.

Practice Exercise

Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.

This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.

FAQ

### What happens if I break the rules of hooks?

React may skip hooks, use stale state, or throw "Rendered fewer hooks than expected." The order of hooks is used internally to match state values across renders. Breaking the order corrupts this mapping, leading to unpredictable behavior and hard-to-debug bugs.

Can I use hooks inside useCallback or useMemo?

No. useCallback and useMemo take callbacks, but those callbacks cannot contain hook calls. Hooks can only be called from the top level of a React function component or another custom hook. Use callbacks to invoke functions, not to declare hooks.

Does the eslint plugin catch all violations?

The eslint-plugin-react-hooks catches most violations, including conditional hooks, hooks in loops, and hooks in nested functions. It does not catch dynamic hook names (like useSomeHook[condition ? 'A' : 'B']()) or hooks called from async functions. Always pair the linter with manual code review.

Built by the developers of DodaTech

Doda Browser, DodaZIP & Durga Antivirus Pro