Immutable updates to nested data
Quick answer
An immutable update creates new objects along the changed path instead of modifying existing caller-owned data. Unchanged branches can be shared.
How it works
For {profile:{name}, settings}, use {...state, profile:{...state.profile, name:newName}}. Copying only the outer object leaves its nested references unchanged. Structural sharing preserves unchanged branch identities and reduces needless allocation, but shared branches must be treated as immutable by convention. Object spread copies enumerable own properties; do not use it as a general class instance clone.
const s={profile:{name:"A"},settings:{dark:true}};const t={...s,profile:{...s.profile,name:"B"}};console.log(s.profile.name,t.profile.name,s.settings===t.settings);Expected output in Node.js:
A B trueOnly the updated path is copied.
const a={nested:{n:1}};const b={...a};b.nested.n=5;console.log(a.nested.n,b.nested===a.nested);Expected output in Node.js:
5 trueThe outer copy retains the same nested reference.
Common mistakes
A shallow copy is not a deep copy. Avoid modifying a shared nested branch after the update.
Practice
Update an order quantity without changing the original and compare identity of its unchanged metadata.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Immutable updates to nested data — Knowledge Check
Reason about the protocol or programming technique and predict the example output.
Which branches need new objects in a typical immutable update?
What does structural sharing retain?
Does object spread recursively clone nested objects?
What is the exact console output in Immutable updates to nested data example 1?
const s={profile:{name:"A"},settings:{dark:true}};const t={...s,profile:{...s.profile,name:"B"}};console.log(s.profile.name,t.profile.name,s.settings===t.settings);What is the exact console output in Immutable updates to nested data example 2?
const a={nested:{n:1}};const b={...a};b.nested.n=5;console.log(a.nested.n,b.nested===a.nested);