JavaScript › Functional Programming
How do you avoid deeply nested, mutation-heavy code when updating nested state immutably?
AdvancedAnswer
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.