Performance: Why deep reactivity understanding matters
This affects how efficiently Vue tracks and updates changes in the UI, impacting rendering speed and responsiveness.
const state = reactive({ user: { name: 'Alice', age: 30 } }); // Update nested properties to keep reactivity state.user.name = 'Bob'; state.user.age = 25;
const state = reactive({ user: { name: 'Alice', age: 30 } }); // Directly replacing nested object without deep reactivity state.user = { name: 'Bob', age: 25 };
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Replacing nested objects | Many DOM updates | Multiple reflows | High paint cost | [X] Bad |
| Updating nested properties directly | Minimal DOM updates | Single reflow | Low paint cost | [OK] Good |
| Using shallowReactive for nested data | Missed updates | No reflows but stale UI | No paint cost but poor UX | [X] Bad |
| Using reactive for nested data | Accurate DOM updates | Minimal reflows | Efficient paint | [OK] Good |
const state = reactive({ profile: { age: 30 } })
function updateAge() {
state.profile.age = 31
}
updateAge()
console.log(state.profile.age)state object is reactive, so nested properties like profile.age are tracked and can be updated.state.profile.age to 31, changing the reactive property.const state = reactive({ items: [{ id: 1, name: 'A' }] })
function addItem() {
state.items.push({ id: 2, name: 'B' })
}
addItem()
console.log(state.items.length)addItem()?items was not wrapped in reactive(), Vue won't detect push changes, so UI won't update.const state = reactive({
user: {
profile: {
settings: { theme: 'light' }
}
}
})
// Later in code
state.user.profile.settings.theme = 'dark'settings was added later like this?const settings = { theme: 'light' }
state.user.profile.settings = settingsPass the test and this pattern moves unknown