Update Nested Object Immutable
- Spread operator does shallow copy only.
- When reference types in an object are copied, the address location is copied, so it still refers to the same object.
- You should avoid deeply nested structures, because the deeper the structure is the more complicated the update logic will be. So prefer a flat structure instead of deeply nested structure.
const [customer, setCustomer] = useState({
name: "Ganesh",
address: {
city: "Chennai"
country: "IN"
}
})
setCustomer({
...customer,
address: {
...customer.address,
city: "Bangalore"
}
})