Performance: toRef and toRefs for destructuring
This concept affects how reactive state is accessed and updated efficiently in Vue components, impacting rendering speed and responsiveness.
const count = toRef(reactiveState, 'count') // count remains reactive and updates UI correctly
const { count } = reactiveState // Using count directly breaks reactivity
| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Direct destructuring of reactive object | No reactive tracking | Triggers full re-render on manual update | High due to forced updates | [X] Bad |
| Using toRef for single property | Reactive tracking preserved | Minimal reflows on change | Low paint cost due to targeted updates | [OK] Good |
| Using toRefs for multiple properties | Reactive tracking preserved for all | Minimal reflows on changes | Low paint cost with efficient updates | [OK] Good |
toRef in Vue's Composition API?toRef doestoRef creates a reactive reference to a single property inside a reactive object, keeping reactivity when destructuring.toRefs creates refs for all properties, not just one. The other options describe different functions.state using toRefs?toRefstoRefs returns an object with refs for each property, so destructuring with curly braces is correct.toRef which returns a single ref, so destructuring multiple properties is invalid. const [count, name] = toRefs(state) uses array destructuring which is wrong. const count = toRefs(state).count accesses a property but does not destructure.const state = reactive({ count: 0, name: 'Vue' })
const { count } = toRefs(state)
count.value++
console.log(state.count)toRefs keeps the properties reactive. So count is a ref linked to state.count.count.value updates state.countcount.value by 1 changes state.count to 1, so logging state.count outputs 1.const state = reactive({ count: 0 })
const { count } = state
count.value++state directly extracts the raw value, losing reactivity. count is not a ref here.count.value++ failscount is a plain value, it has no .value property, so this causes an error.user with properties firstName and lastName. You want to destructure these properties but keep them reactive and also create a computed property fullName that updates when either changes. Which approach correctly achieves this?toRefs keeps firstName and lastName reactive refs when destructured.firstName.value and lastName.value to reactively update fullName.Pass the test and this pattern moves unknown