React has a strict rule:
Don't call hooks inside loops, conditions, or nested functions.
This isn’t just a style preference, it’s required for React to work correctly.
If you break this rule, you’ll run into bugs that are hard to trace. Here's exactly why this rule exists and what React is doing under the hood that makes it necessary.
Here's what’s actually going on:
React doesn’t track your hooks by name instead it tracks them by order of execution.
So when your component renders, React expects something like this:
1st hook → useState
2nd hook → useEffect
3rd hook → useRef
This order must stay the same every render.
If it doesn't? React pulls the wrong state out of the wrong slot, and now your useRef is getting count’s value and chaos begins 🧨
## Here's the kind of code that breaks things:
On one render, useState is there.
On the next? It's skipped.
Bug time! 🐞
✅ The fix? Simple rule:
Call all your hooks at the top level, and in the same order on every render.
No if, no for, no function inside a function.
🎯 The takeaway:
React’s rules around hooks might seem strict, but they exist for a reason: to ensure your state and side effects are predictable and consistent. By following these simple guidelines, you can avoid tricky bugs and keep your app running smoothly.
If you’ve ever run into strange issues with hooks, this might be the explanation you’ve been looking for. Stay consistent, keep your hooks at the top level, and React will handle the rest.
Got a hook-related bug story of your own? Drop it in the comments, or let me know if this helped clear things up! 👇