MediumHooks & Closures💻 Output Question

Hook call order must be stable — cursor-based tracking

💡

Hint

React identifies each hook by its call ORDER — not its name. That's why hooks can't be called conditionally: skipping one shifts every subsequent hook to the wrong slot.

What does this output?

// Simulates React's hook tracking by call order
const hooks = [];
let cursor = 0;

function useState(init) {
  const i = cursor++;
  if (hooks[i] === undefined) hooks[i] = init;
  const setState = v => { hooks[i] = v; };
  return [hooks[i], setState];
}

function resetCursor() { cursor = 0; }

// Render 1
resetCursor();
const [a, setA] = useState('first');
const [b, setB] = useState('second');
console.log(a, b);

// State update
setA('FIRST');

// Render 2
resetCursor();
const [a2, setA2] = useState('first');
const [b2, setB2] = useState('second');
console.log(a2, b2);

Correct Output

first second
FIRST second

Why this output?

Explanation: cursor=0: slot 0 gets 'first', slot 1 gets 'second'. setA updates slot 0. cursor resets: slot 0 now has 'FIRST', slot 1 still 'second'.

Key Insight: React identifies each hook by its call ORDER — not its name. That's why hooks can't be called conditionally: skipping one shifts every subsequent hook to the wrong slot.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz