Beginner LevelVue JS
What is the difference between ref() and reactive() in Vue 3?
❓ Interview Prompt: Explain when to use ref vs reactive, how ref unwrapping works in templates, and destructuring limitations.
Both 'ref()' and 'reactive()' create reactive state in Vue 3's Composition API, but handle data differently:
'ref(value)':
•
Can store any data type (primitives like string/number/boolean, OR objects/arrays).
•
Wraps the value in an object with a '.value' property ('count.value').
•
In templates, 'ref' is automatically unwrapped, so you write '{{ count }}' instead of '{{ count.value }}'.
'reactive(object)':
•
Can only store object types (objects, arrays, Maps, Sets). Cannot store primitives!
•
Uses ES6 Proxies directly. No '.value' needed in JavaScript or templates.
•
Limitation: Destructuring or reassigning a 'reactive()' object destroys its reactivity link! ('let { name } = reactiveObj' makes 'name' non-reactive).
Best Practice:
Use 'ref()' for almost everything. It is more consistent and immune to destructuring bugs when using 'toRefs()'.
Code Implementation Example
javascript
import { ref, reactive, toRefs } from 'vue';
// 1. ref works with primitives and objects
const count = ref(0);
count.value++; // Access via .value in JS
// 2. reactive works ONLY with objects
const user = reactive({ name: 'Alice', age: 28 });
user.age++; // Access directly without .value
// ❌ Destructuring reactive destroys reactivity!
let { name } = user;
name = 'Bob'; // Does NOT update the UI or user.name!
// ✅ Fix: Use toRefs to safely destructure into individual refs
const { name: safeName, age: safeAge } = toRefs(user);
safeName.value = 'Bob'; // ✅ Reactive!💡ref vs reactive behavior and safe destructuring with toRefs.
🎯 Interview Key Takeaway
Use ref() as your default choice for reactive state. Use reactive() only for cohesive object forms that are never destructured.
#ref#reactive#Reactivity#Beginner
Back to all Vue JS Questions→