⚠️ Can I Use React Hooks Inside Loops or Conditions?
Short answer: ❌ No, you can’t use React hooks inside loops, conditions, or nested functions.
If you do, you'll likely see this dreaded error:
"React has detected a violation of the Rules of Hooks..."
Let’s explore why this happens, what the official rules say, and how to fix it properly.
📜 The Rules of Hooks (by React)
-
Only call hooks at the top level.
-
Only call hooks from React function components or custom hooks.
These rules are strict and enforced by tools like the ESLint plugin for React hooks.
🚫 Why You Can't Use Hooks Inside Loops or Conditions
Hooks rely on the order in which they’re called. If you call a hook conditionally or inside a loop, the order may change on the next render, which breaks React’s internal tracking.
🔁 Example That Will Break:
if (isLoggedIn) { const [user, setUser] = useState(null); // ❌ Wrong! }
If isLoggedIn
is false on one render and true on the next, useState
will be skipped and React will lose sync — causing weird bugs or crashes.
✅ How to Fix It
Always declare hooks unconditionally at the top level of your component.
✔️ Correct Approach:
const [user, setUser] = useState(null); if (isLoggedIn) { // Use the state here conditionally return <Dashboard user={user} />; }
Or use conditional values, not conditional hooks.
🔁 What About Loops?
You also cannot use hooks inside a for
or while
loop.
❌ This Will Break:
for (let i = 0; i < items.length; i++) { const [value, setValue] = useState(null); // ❌ Invalid }
✔️ Correct Alternative:
Use a custom hook to manage state in each item, or store them in an array.
🛠️ Real Use Case Fix Example
Instead of:
if (someCondition) { useEffect(() => { // effect }, []); }
Do:
useEffect(() => { if (someCondition) { // effect } }, [someCondition]);
✅ Conclusion
-
❌ Don’t call React hooks inside if statements, loops, or nested functions.
-
✅ Always call hooks at the top level of your component or custom hook.
-
🔄 Use conditions inside the hook, not around it.
Following the Rules of Hooks helps React maintain consistent hook order between renders and avoids hard-to-debug issues.
🔍 Tip: Use the official eslint-plugin-react-hooks to catch violations early.