Calling Hooks Inside Loops
What you'll learn: Why placing hooks inside for or while loops destroys React's ability to track state correctly.
The Order Corruption Problem
Remember that React relies on call order to match each hook to its stored value. When you put a hook inside a loop, the number of times that hook executes changes between renders — and this shatters React's index-based tracking system.
function BrokenComponent({ items }) {
// ❌ NEVER DO THIS
for (let i = 0; i < items.length; i++) {
const [value, setValue] = useState(items[i]);
// This creates a different number of hooks each render!
}
return <div>...</div>;
}
If items has 3 elements on first render, React registers 3 useState hooks. If items later has 5 elements, React now expects 5 hooks but your component's structure suddenly changed. The hook at index 0 might now receive the value that belonged to index 2. Complete chaos.
Why This Destroys State
React's internal hook array expects the exact same number of hooks in the exact same order every single render. A loop whose iteration count varies makes that impossible. The state values get misaligned, assigned to the wrong variables, and your component becomes unpredictable.
The Correct Approach
Call hooks at the top level, then use the loop after all hooks are called:
function CorrectComponent({ items }) {
// ✅ All hooks called unconditionally first
const [values, setValues] = useState(items);
// Loop happens AFTER hooks
return (
<div>
{values.map(item => <div key={item.id}>{item.name}</div>)}
</div>
);
}
Key Takeaway: Hooks inside loops create variable hook counts between renders, corrupting React's order-based state tracking. Always call all hooks at the top level before any loops execute.