CKTIS / JavaScript
Immutable updates and structural sharing
Create a new state without mutating the previous version: copy the containers along the update path and reuse unchanged branches.
Version: ECMAScript 2024 and the current web platform; runtime support varies
Syntax
const next = { ...state, profile: { ...state.profile, name: newName } };
const nextItems = items.with(index, replacement);Immutable updates and structural sharing work together: build a new version of the state without writing into the previous one. For tree-shaped state, create new containers from the root to the point of change and reuse the same objects in unaffected branches. That reuse is structural sharing. For objects, === tests identity, not matching contents. If nothing changes, you can return the original root.
Object spread ... makes a shallow copy of the values of own enumerable properties. It does not copy the source prototype, and a later entry with the same key overrides an earlier one. { ...state } alone does not copy state.profile: writing to profile.name through that shallow copy would also change the previous version. Do not mutate shared branches through any reference.
For arrays, items.with(index, replacement) returns a new array without writing to items and preserves object identity at the other positions. Negative indices count from the end; an index that is out of bounds after normalization throws a RangeError. Copying along the path skips entire unchanged branches, but it still copies entries in each rebuilt container, so copying one large array can still be costly.
Array.prototype.with is part of ECMAScript 2024; check support in your target runtime. structuredClone() is a separate web-platform API: for an ordinary tree of cloneable data, it makes a deep copy rather than sharing branches with the source. Not all values can be cloned; for example, a function causes a DataCloneError.
Examples
{
const state = {
profile: { name: "Ada" },
settings: { theme: "dark" },
};
const next = {
...state,
profile: { ...state.profile, name: "Grace" },
};
console.log(`names: ${state.profile.name} -> ${next.profile.name}`);
console.log(`same root: ${state === next}`);
console.log(`same profile: ${state.profile === next.profile}`);
console.log(`same settings: ${state.settings === next.settings}`);
}Result
names: Ada -> Grace same root: false same profile: false same settings: true
`state.profile.name` is still `Ada`, while `next.profile.name` is `Grace`. The root and `profile` are new objects; `settings` is the same object in both versions.
Related lessons
- JavaScript · Lesson 18 · Advanced · Version: 4