Dùng spread operator để tạo bản sao ở mỗi cấp: setState(prev => ({ ...prev, user: { ...prev.user, name: 'new' } })).
- Với nested sâu, xem xét dùng Immer library cho phép viết code mutate nhưng tạo immutable update dưới hood.
- Cấu trúc state phẳng (flat) cũng giúp tránh vấn đề này.
Use the spread operator to create a shallow copy at each level: setState(prev => ({ ...prev, user: { ...prev.user, name: 'new' } })).
- For deeply nested structures, consider the Immer library, which lets you write mutating-style code while producing immutable updates under the hood.
- Keeping state as flat as possible also avoids this problem entirely.