Copy objects without mutation
Change data without changing the original
Mutation changes an existing object or array. React state should be treated as read-only: build a replacement and later pass it to the state setter. This lets earlier render snapshots retain their meaning. In ordinary JavaScript, assigning an object to a second variable does not copy it. The two variables refer to the same object.
const profile = {name: "Mina", points: 2};const alias = profile;const next = {...profile, points: 3};console.log(alias === profile);console.log(next === profile);console.log(profile.points, next.points);The output is true, false, then 2 3. Strict equality compares object identity, not the contents. Object spread copies enumerable own properties into a new object; the later points property replaces the copied value. The original stays at 2. A const binding prevents reassignment, not mutation of the object it holds.
Destructure and copy nested data
Destructuring extracts values from a structure. For example, const {name} = profile creates a binding for the name property. Rest syntax gathers remaining properties: const {name, ...details} = profile. Spread syntax expands values into a new object or array. A shallow copy shares nested objects, so copy each level along the path you change.
const settings = {name: "Nora", preferences: {theme: "light", compact: false}};const {name, ...details} = settings;const next = {...settings, preferences: {...settings.preferences, theme: "dark"}};console.log(name, details.preferences.theme);console.log(settings.preferences.theme, next.preferences.theme);console.log(settings.preferences === next.preferences);The result shows Nora light, then light dark, then false. details is a new outer object but shares the original preferences. The replacement next has its own preferences object because that nested level was also copied. Unchanged branches may be reused safely when they are not mutated.
Update a single item in an array
const tasks = [{id: 1, done: false}, {id: 2, done: false}];const updated = tasks.map(task => task.id === 2 ? {...task, done: true} : task);console.log(JSON.stringify(updated));console.log(tasks[1].done, updated[0] === tasks[0]);The conditional expression condition ? first : second picks one result. The new array has the second task marked done, while the original second task remains false. The first object is reused. To append without changing the existing array, use [...tasks, newTask]. Avoid calling mutating methods such as push or sort directly on React state.
Common mistake: copying only the outside
If copy = {...settings}, then copy.preferences.theme = "dark" also changes the original nested preferences. Copy the nested object before assigning its new value, as in the second example. Do not assume every object needs a full deep clone; copying only the changed path is often enough. Practice the approach before using state setters in Chapter 10.