Performance: Ref and reactive in Composition API
This affects how Vue tracks changes and updates the DOM efficiently during user interactions.
import { ref, reactive } from 'vue'; const count = ref(0); const user = reactive({ name: 'Alice', age: 30 });
import { reactive } from 'vue'; const count = reactive({ value: 0 }); const user = reactive({ name: 'Alice', age: 30 });
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Using reactive for primitives | More proxy layers | Multiple re-renders | Higher paint cost | [X] Bad |
| Using ref for primitives | Minimal proxy layers | Single re-render | Lower paint cost | [OK] Good |
| Replacing nested reactive objects | Triggers full reactivity recalculation | Multiple reflows | Higher paint cost | [X] Bad |
| Mutating nested reactive properties | Fine-grained updates | Single reflow | Lower paint cost | [OK] Good |
ref and reactive?ref usageref holds simple reactive values like numbers or strings and requires accessing the value with .value.reactive usagereactive wraps objects or arrays to make their properties reactive and accessed directly without .value.ref is for simple values accessed with .value, reactive is for objects and arrays accessed directly. -> Option Creactive is used to wrap objects to make their properties reactive.ref with an object, which is allowed but requires .value to access. const state = reactive({ count: 0 }) correctly uses reactive with an object. const state = reactive(0) uses reactive with a number, which is invalid. const state = ref(0) uses ref with a number, which is valid but not for objects.import { ref, reactive } from 'vue';
const count = ref(0);
const state = reactive({ clicks: 0 });
count.value++;
state.clicks++;
console.log(count.value, state.clicks);count is a ref holding 0, incremented by count.value++ to 1. state is reactive object with clicks 0, incremented by state.clicks++ to 1.count.value and state.clicks will print 1 1.import { ref } from 'vue';
const user = ref({ name: 'Alice' });
user.name = 'Bob';ref wraps the object, so to access or update properties inside, you must use .value.user.name directly, which is incorrect. It should be user.value.name.name (string) and tags (array). You also want to track a simple counter for submissions. Which setup correctly uses ref and reactive together?reactive is best to wrap the object with name and tags properties.ref is appropriate to track it reactively.Pass the test and this pattern moves unknown