How to Fix React Hooks Rules Violation
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-hooksplugin. - 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
- Misunderstanding that
Stringis[Char]with poor performance for large text operations - Using
foldlinstead offoldl'causing stack overflow on large lists - 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
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro