Object Spread
π¨βπΌ Object spread is how we update objects without mutation. This is critical
for React state updates where mutation doesn't trigger re-renders.
// Create a new object with updated values
const original = { name: 'Alice', age: 30 }
const updated = { ...original, age: 31 }
// updated = { name: 'Alice', age: 31 }
// original is unchanged!
Order Matters
Later properties override earlier ones:
const defaults = { theme: 'light', fontSize: 14 }
const userPrefs = { fontSize: 18 }
const settings = { ...defaults, ...userPrefs }
// { theme: 'light', fontSize: 18 }
Nested Objects
Spread is shallowβnested objects need explicit spreading:
const user = { name: 'Alice', address: { city: 'NYC' } }
const updated = {
...user,
address: { ...user.address, city: 'LA' },
}
- Use object spread to create an updated user object
- Merge two configuration objects with spread
- Update a nested object immutably
π° Spreading with override:
const updated = { ...original, propertyToChange: newValue }
π MDN - Spread Syntax