ref & reactive — Series 2

Preview — 3 of 10 questions

Why does destructuring state directly lose reactivity, while destructuring toRefs(state) doesn't?

javascript
import { reactive, toRefs } from 'vue'

const state = reactive({ name: 'Ada', age: 28 })

// Plain destructuring
const { name } = state
// vs.
const { name: name2 } = toRefs(state)
ANeither approach loses reactivity — this is a common misconception
BtoRefs() deep-clones state, so name2 is a totally independent copy that happens to start with the same value
CPlain destructuring copies the current value out of state at that moment — name becomes a disconnected plain string. toRefs() instead creates a ref per property, each linked back to the source object via getter/setter, so name2.value stays in sync with state.name
DtoRefs() only works on ref()s, not reactive() objects — this code throws

What does isRef(value) return for each of these?

javascript
import { ref, reactive, isRef } from 'vue'

const a = ref(0)
const b = reactive({ count: 0 })
const c = 42
const d = ref(0).value

console.log(isRef(a)) // ?
console.log(isRef(b)) // ?
console.log(isRef(c)) // ?
console.log(isRef(d)) // ?
AAll four calls return true — isRef() considers any reactive-adjacent value a ref
BisRef(a) and isRef(b) are both true, since both are created by Vue's reactivity APIs; isRef(c) and isRef(d) are false
CAll four calls return false — isRef() is deprecated and always returns false in Vue 3
DisRef(a) is true; the other three are false — isRef() specifically checks whether its argument is a ref object (something with an internal .value and Vue's ref marker), not a reactive object, a plain value, or an already-unwrapped .value

What does unref(source) return for each of these calls?

javascript
import { ref, unref } from 'vue'

const count = ref(5)
const plainNumber = 10

console.log(unref(count))       // ?
console.log(unref(plainNumber)) // ?
Aunref(count) returns 5 (the unwrapped value); unref(plainNumber) returns 10 unchanged — unref() is shorthand for "if this is a ref, return .value; otherwise, return the value as-is," letting code handle "maybe a ref, maybe not" arguments uniformly
Bunref() throws a TypeError when given a plain, non-ref value like 10
Cunref(count) returns the ref object itself, unchanged; unref() only unwraps nested refs inside reactive objects, not top-level refs
Dunref() and .value are unrelated — unref() is only for reactive() objects, never for ref()s

Sign up free to play

Answer all 10 questions (7 more), see explanations for every answer, and track your score.