Performance: Shallow ref and shallow reactive
This affects how Vue tracks changes and updates the DOM, impacting rendering speed and responsiveness.
const state = shallowReactive({ user: { name: 'Alice', age: 30, address: { city: 'NY', zip: '10001' } } });
const state = reactive({ user: { name: 'Alice', age: 30, address: { city: 'NY', zip: '10001' } } });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Deep reactive/ref | Many nested watchers | Multiple reflows on nested changes | High paint cost due to frequent updates | [X] Bad |
| Shallow reactive/ref | Watchers only on top-level | Single reflow per top-level change | Lower paint cost, fewer updates | [OK] Good |
shallowRef in Vue track reactively?shallowRef tracks reactivity only when the reference changes, not inside nested objects.ref or reactive, it does not track nested property changes.shallowReactive is used to create a shallow reactive object that tracks only top-level properties.reactive creates deep reactivity, shallowRef and ref create refs, not shallow reactive objects.const state = shallowReactive({ count: 0, nested: { value: 1 } });
state.nested.value = 2;
console.log(state.nested.value);state.nested.value = 2 changes the nested object property directly, so the value updates.const state = shallowRef({ count: 0, nested: { value: 1 } });
state.value.nested.value = 5;
console.log(state.value.nested.value);shallowRef tracks only changes to the reference itself, not nested properties inside the object.state.value.nested.value updates the nested property but does not trigger Vue reactivity updates.const state = shallowReactive({ user: { name: 'Alice', age: 30 } });
watch(() => state.user, (newVal, oldVal) => {
console.log('User changed:', newVal);
});
state.user.name = 'Bob';shallowReactive tracks only top-level properties reactively. The watch on state.user triggers only if the user object reference changes.state.user.name mutates a nested property but does not replace the user object, so the watch callback does not run.state.user is replaced entirely -> Option APass the test and this pattern moves unknown