Navigate
Search topics, hooks, and fundamentals
The spread operator creates a shallow copy — like making a mold of a pot. Perfect for flat objects, but watch out for nested ones.
The spread operator (...) copies all properties from one object into a new one:
// Spread = make a new pot with the same properties
const original = { color: "red", size: "large" };
const copy = { ...original };
copy.color = "blue";
console.log(original.color); // "red" — safe!
console.log(copy.color); // "blue"The most common React pattern — spread the old state, then override what changed:
// Spread + override = common React pattern
const pot = { color: "red", size: "large", glaze: "matte" };
const updated = {
...pot, // copy all properties
color: "blue", // override just this one
};
// { color: "blue", size: "large", glaze: "matte" }Original
color: "red"
size: "large"
glaze: "matte"
Overrides
(none yet)
Result
color: "red"
size: "large"
glaze: "matte"
Spread only copies one level deep. Nested objects are still shared by reference:
// SHALLOW copy — nested objects are still shared!
const pot = {
color: "red",
details: { weight: 500, origin: "Japan" },
};
const copy = { ...pot };
copy.details.weight = 300; // MUTATES the original!
console.log(pot.details.weight); // 300 — not 500!
// The spread only copied the top levelWatch what happens when you modify a nested property through a shallow copy:
When updating nested state, spread at every level that contains a change:
// Deep copy of nested objects
const updated = {
...pot,
details: {
...pot.details, // spread the nested object too
weight: 300, // override nested property
},
};
// Now pot.details.weight is still 500 ✅{ ...obj } creates a shallow copy — new object, same nested refsuseReducer or Immer