MediumState & Immutability💻 Output Question

Nested state requires full spread chain

💡

Hint

Spread only creates a shallow copy. For nested state, you must spread at every level you want to change. Libraries like Immer handle this automatically.

What does this output?

const state = {
  user: { name: 'Alice', prefs: { theme: 'light' } }
};

// Wrong — only shallow copy, nested still shared
const wrongUpdate = { ...state, user: { ...state.user } };
wrongUpdate.user.prefs.theme = 'dark';

// Correct — copy all the way down
const correctUpdate = {
  ...state,
  user: {
    ...state.user,
    prefs: { ...state.user.prefs, theme: 'dark' }
  }
};

console.log(state.user.prefs.theme);      // was wrongUpdate's mutation applied?
console.log(wrongUpdate.user.prefs.theme);
console.log(correctUpdate.user.prefs.theme);
console.log(state.user.prefs === correctUpdate.user.prefs);

Correct Output

dark
dark
dark
false

Why this output?

Explanation: wrongUpdate only deep-copies one level. prefs is still the same reference — mutating wrongUpdate.user.prefs.theme mutates the original. correctUpdate creates a new prefs object, so it's independent.

Key Insight: Spread only creates a shallow copy. For nested state, you must spread at every level you want to change. Libraries like Immer handle this automatically.

Practice predicting output live →

66 output questions with instant feedback

💻 Try Output Quiz