Vue.js Developer interview question · Most asked
ref or reactive: what is the difference, and when do you use each?
Summary
ref() wraps any value (primitives included) in an object with a .value property; reactive() makes an object deeply reactive through a Proxy and only works with objects. The Vue docs recommend ref() as the primary API because reactive() has limitations.
Longer Answer
reactive() limitations: it cannot hold primitives; replacing the whole object breaks the reactive connection (state = reactive({...}) again loses tracking for existing references); and destructuring or passing a property to a function loses reactivity (const { count } = state is a plain number). ref avoids these: you can reassign .value freely. Refs are automatically unwrapped in templates and when nested inside reactive objects (but not inside arrays or Maps).
toRefs(state) converts a reactive object's properties into refs so destructuring keeps reactivity, a common pattern when returning state from composables.
Code Example
import { ref, reactive, toRefs } from "vue";
const count = ref(0);
count.value++; // template: {{ count }} (auto-unwrapped)
const state = reactive({ user: null, loading: false });
const { loading } = toRefs(state); // stays reactive
Key Points
- ref: any value,
.value. - reactive: objects only, Proxy-based.
- Destructuring reactive loses reactivity.
- Docs recommend ref by default; toRefs for destructuring.
More most-asked Vue.js Developer questions
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- What are composables, and why did they replace mixins?
- computed, watch or watchEffect: when do you use each?
- Options API or Composition API: what is the difference, and which would you use?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?