Middle
Why can't hooks be called inside conditions or loops?
sobes.tech AI
Answer from AI
React hooks must be called at the top level of a component and not inside conditions or loops because React relies on the order of hook calls to correctly associate state and effects between renders.
Calling a hook inside a condition or loop can change the number of hook calls across renders, causing React to lose synchronization, which may lead to errors or incorrect behavior.
Incorrect usage example:
if (someCondition) {
useEffect(() => { /* ... */ });
}
Correct usage:
useEffect(() => {
if (someCondition) {
// logic
}
}, [someCondition]);
Thus, hooks should always be called in the same order.