MediumState & Immutability💻 Output Question

Shallow merge vs replace in state updates

💡

Hint

Critical difference: Class setState shallowly merges. useState fully replaces. With hooks, always spread the previous state: setState(prev => ({ ...prev, x: 99 })).

What does this output?

// Class component setState merges (shallow)
let classState = { x: 1, y: 2, z: 3 };
function classSetState(update) {
  classState = { ...classState, ...update }; // shallow merge
}

// Hooks useState replaces
let hookState = { x: 1, y: 2, z: 3 };
function hookSetState(update) {
  hookState = update; // full replace
}

classSetState({ x: 99 });
console.log(classState.y); // still has y?

hookSetState({ x: 99 });
console.log(hookState.y); // still has y?

Correct Output

2
undefined

Why this output?

Explanation: Class setState merges — y:2 and z:3 are preserved. Hook useState replaces — the new state { x: 99 } has no y or z.

Key Insight: Critical difference: Class setState shallowly merges. useState fully replaces. With hooks, always spread the previous state: setState(prev => ({ ...prev, x: 99 })).

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz