React Hook Positioning Bug Fix: Move Hooks Above Early Returns

My React app crashed in production yesterday. The error? "Rendered fewer hooks than expected." The fix was exactly 2 lines of code 👇 I had this component: ❌ const MySection = () => { const store = useAppSelector(...) // Hook 1 if (!isVisible) return null // early exit const data = useMemo(...) // Hook 2 — SKIPPED! } When a user toggled visibility, React saw 2 hooks on render 1 but only 1 hook on render 2. Instant crash. 💥 The thing most devs don't realize: React doesn't track hooks by name. It tracks them by POSITION — like slots in an array. Slot 0 → useAppSelector Slot 1 → useMemo Skip one? Every hook below it reads the wrong slot's data. Think of it like filling a form top-to-bottom. Skip field 2, and field 3's answer lands in field 2's box. The fix: ✅ const MySection = () => { const store = useAppSelector(...) // Hook 1 — always runs const data = useMemo(...) // Hook 2 — always runs if (!isVisible) return null // safe here! } Move ALL hooks above ANY early return. That's it. 3 rules you must never break: → No hooks inside if/else blocks → No hooks after early returns → No hooks inside loops I found this same bug hiding in 2 other components in the same codebase. The app worked fine for months — until someone toggled the right button. What's the sneakiest React bug you've shipped to production? 👇 ——— ♻ Repost to save a fellow React dev from this bug 📕 Save this for your next code review 💡 Follow Abhay Rana for more visual React breakdowns #ReactJS #WebDevelopment #JavaScript #FrontendDevelopment #CodingTips

  • graphical user interface

Many devs don’t realize that React tracks hooks via a Singly Linked List on the Fiber node using a workInProgressHook pointer. When you skip a hook through an early return, you’re not just skipping logic—you’re misaligning that pointer. React then tries to read the state of 'Hook 3' from the memory slot of 'Hook 2'.

Even better would be further decomposition, so all of the computation will happen in the children component, and the parent will decide whether to render it or not. Single responsibility principle.

Like
Reply
See more comments

To view or add a comment, sign in

Explore content categories