What happens if Hooks are called conditionally in React?
In React, Hooks must always be called in the same order on every render.
If Hooks are called conditionally (inside if, loops, or nested functions), React can lose track of which Hook belongs to which state/effect, causing bugs and errors.
Why does this happen?
React internally identifies Hooks by their call order, not by their names.
Example:
const [count, setCount] = useState(0); // Hook #1
const [name, setName] = useState(""); // Hook #2
React remembers:
-
Hook 1 →
count -
Hook 2 →
name
If on the next render one Hook is skipped because of a condition, the ordering changes and React gets confused.
Wrong Example (Conditional Hook)
function MyComponent({ show }) {
if (show) {
useEffect(() => {
console.log("Shown");
}, []);
}
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
Problem
-
First render with
show = true-
useEffect→ Hook #1 -
useState→ Hook #2
-
-
Next render with
show = false-
useStatebecomes Hook #1
-
Now React mismatches the Hooks.
This can cause:
-
Incorrect state values
-
Effects running incorrectly
-
Rendering bugs
-
Runtime errors
Common Error Message
You may see errors like:
Rendered fewer hooks than expected.
or
React Hook "useEffect" is called conditionally.
Correct Approach
Call Hooks at the top level of the component.
Move conditions inside the Hook instead.
Correct Example
function MyComponent({ show }) {
useEffect(() => {
if (show) {
console.log("Shown");
}
}, [show]);
const [count, setCount] = useState(0);
return <div>{count}</div>;
}
Now:
-
Hooks are always called in the same order
-
React works correctly
Rules of Hooks
Hooks should:
Be called at the top level
Be called in React functional components
Be called in custom Hooks
Hooks should NOT:
Be called conditionally
Be called inside loops
Be called inside nested functions
Be called inside class components
Interview-Friendly Explanation
React relies on the order of Hook calls to preserve state between renders. If Hooks are called conditionally, the order may change between renders, causing React to associate state and effects incorrectly. Therefore, Hooks must always be called unconditionally at the top level of the component.
Quick Interview Answer
Hooks should never be called conditionally because React tracks Hooks by call order. If the order changes between renders, React can mismatch state and effects, leading to bugs and runtime errors. Always call Hooks at the top level and place conditions inside the Hook instead.
