let state = {
user: { name: 'Alice', age: 30 },
settings: { theme: 'light', notifications: true },
};
function setState(update) {
state = { ...state, ...update };
}
// Bug: replacing settings entirely — notifications lost
setState({ settings: { theme: 'dark' } }); // notifications disappears!
console.log(state.settings.theme);
console.log(state.settings.notifications);
console.log(state.user.name);let state = {
user: { name: 'Alice', age: 30 },
settings: { theme: 'light', notifications: true },
};
function setState(update) {
state = { ...state, ...update };
}
// Fix: spread the nested object to preserve siblings
setState({ settings: { ...state.settings, theme: 'dark' } });
console.log(state.settings.theme);
console.log(state.settings.notifications);
console.log(state.user.name);Bug: { settings: { theme: 'dark' } } replaces the entire settings object. notifications: true is lost because the new settings has no notifications key.
Explanation: ...state.settings copies all existing settings first, then theme: 'dark' overrides only the theme. notifications and any other settings are preserved.
Key Insight: When updating nested state, spread at every level: { ...state, settings: { ...state.settings, theme: 'dark' } }. Each level needs its own spread.