What is Vue's reactivity in depth — ref vs reactive?
Why Interviewers Ask This
Mid-level Vue.js roles require deep understanding of this topic. Interviewers ask this to separate candidates who truly understand the mechanics from those who only know surface-level concepts.
Answer
Understanding when to use ref() vs reactive() is important for Vue 3 Composition API: ref(): wraps a value in a reactive wrapper object with a .value property. Works for ANY type (primitives, objects, arrays). const count = ref(0); const user = ref({ name: "Alice" }); count.value++; user.value.name = "Bob";. In templates, .value is automatically unwrapped. Refs maintain identity — reassigning user.value = newUser is reactive. reactive(): creates a reactive proxy of a plain object (not for primitives — they can't be proxied). Returns the proxy directly (no .value). const state = reactive({ count: 0, name: "Alice" }); state.count++;. Key limitation of reactive(): losing reactivity when destructuring or when the reactive object is reassigned: const { count } = state; // count is no longer reactive!. Fix: use toRefs(state) which converts each property to a ref: const { count, name } = toRefs(state); — count.value is now reactive. When to use which: ref for primitive values, standalone variables; reactive for objects with related properties treated as a unit. Many Vue developers prefer using ref for everything (more consistent, easier to track) — the auto-unwrapping in templates removes the .value awkwardness. Vue team recommends ref() as the primary API. toRef(): create a ref for a single property of a reactive object: const count = toRef(state, "count");
Pro Tip
Before answering, structure your response: one-line definition → real-world analogy → concrete example from a project. This makes even complex Vue.js answers easy to follow.
Previous
What is the Composition API and how do composables work?
Next
What are Vue 3 Teleport and Suspense?
More Vue.js Questions
View all →- Intermediate What is the Composition API and how do composables work?
- Intermediate What are Vue 3 Teleport and Suspense?
- Intermediate What is Vue's virtual DOM and how does the diffing algorithm work?
- Intermediate What is Vue's reactivity with watchEffect and its nuances?
- Intermediate What is Vue's component communication patterns?