JavaScript › Functional Programming

How do you avoid deeply nested, mutation-heavy code when updating nested state immutably?

Advanced

Answer

Use spread syntax (or structuredClone/immutable libraries like Immer) to create new objects/arrays at each level being changed, copying siblings shallowly while replacing only the path that changed — avoiding direct mutation of nested structures.
const state = { user: { profile: { age: 30 } } };
const updated = {
  ...state,
  user: {
    ...state.user,
    profile: { ...state.user.profile, age: 31 }
  }
};
Real-world example Updating a single deeply nested field in Redux or React state without mutating the original state object.

Common follow-ups: How does a library like Immer simplify this compared to manual spreading?