Immutable Updates For Nested Objects
Rebuilding each level along a changed path with spread keeps untouched branches reference-identical, so equality checks and memoization stay cheap.
Code
// State trees update by rebuilding the changed path; untouched branches
// keep their identity so equality checks stay cheap.
const state = {
user: { name: 'ada', roles: ['viewer', 'editor'] },
projects: { p1: { title: 'site', done: false }, p2: { title: 'blog', done: true } },
};
// Rebuild each level along the path with spread instead of mutating.
const nextState = {
...state,
user: {
...state.user,
roles: state.user.roles.filter((role) => role !== 'viewer'),
},
projects: {
...state.projects,
p1: { ...state.projects.p1, done: true },
},
};
console.log('old roles:', state.user.roles);
console.log('new roles:', nextState.user.roles);
console.log('p1 done :', state.projects.p1.done, '->', nextState.projects.p1.done);
// p2 was never touched: same object reference inside a new wrapper.
console.log('p2 shared:', state.projects.p2 === nextState.projects.p2);
console.log('wrapper rebuilt:', state.projects !== nextState.projects);Output
Captured from a sandboxed run of this snippet in the build pipeline.
old roles: [ 'viewer', 'editor' ]
new roles: [ 'editor' ]
p1 done : false -> true
p2 shared: true
wrapper rebuilt: trueHow it works
Everything operates on top-level bindings: state, nextState.
What to watch for
- Nothing to vet in a supply-chain review — the file pulls in no packages.
Putting the pieces to work
Expect labeled output — old roles:, new roles:, p1 done : — when the file runs.
Interactive Tools for This Topic
FAQ
- Which packages does this snippet need?
- None. Every symbol the code uses resolves inside the standard library. Its state lives in module-level bindings: `state`, `nextState`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.