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.
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);dark dark dark false
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.