Skip to content

QuizNot attempted

Conditionally calling a hook

showExtra toggles between renders (true then false). What happens?
function App({ showExtra }) {
const [a, setA] = useState(0);
if (showExtra) {
const [b, setB] = useState(0);
}
const [c, setC] = useState(0);
return <div>{a}-{c}</div>;
}
1–4 to choose, Enter to submit
Show answer & explanation

Correct answer:

  • Violates the Rules of Hooks — calling hooks conditionally breaks hook call order, causing React to throw an error or produce inconsistent state
  • Hooks are matched to their state by call order
  • when showExtra flips to false, the second useState call now gets b's slot and React detects the changed hook count (it throws 'Rendered fewer hooks than expected'), so this violates the Rules of Hooks.
  • Not 'React handles it': React has no names for hooks, only positions.
  • Not 'b merges into c' or 'c is frozen': the failure is a hook-order error (or corrupted state slots), not a defined merge.
  • Move the condition inside the hook or into a child component.