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' },
}
🐨 Open and:
  1. Use object spread to create an updated user object
  2. Merge two configuration objects with spread
  3. Update a nested object immutably
πŸ’° Spreading with override:
const updated = { ...original, propertyToChange: newValue }

Please set the playground first

Loading "Object Spread"
Loading "Object Spread"