Immutability and Structural Updates

Immutability means treating existing data as unchanged and producing new values when state changes. JavaScript does not make objects immutable by default, so application code must choose appropriate techniques.

Immutability is particularly valuable in state management because reference identity can efficiently signal that something changed.

Immutable Object Update
const user = {
  name: 'Suriya',
  preferences: {
    theme: 'light'
  }
};

const updatedUser = {
  ...user,
  preferences: {
    ...user.preferences,
    theme: 'dark'
  }
};

console.log(user.preferences.theme);
console.log(updatedUser.preferences.theme);
💡 The original nested object remains unchanged. New objects are created along the path that changed.
Key Takeaways
  • Spread syntax creates shallow copies.
  • Nested updates require copying each changed level.
  • Immutability makes state transitions easier to reason about.
Knowledge Check

Does object spread perform a deep clone?