Ref vs Reactive in Vue: Key Differences and When to Use Each
ref creates a reactive reference to a single value, while reactive makes an entire object reactive. Use ref for primitives and simple reactivity, and reactive for complex objects with multiple properties.Quick Comparison
This table summarizes the main differences between ref and reactive in Vue.
| Aspect | ref | reactive |
|---|---|---|
| Type of value | Single primitive or object wrapped in a ref object | Whole object made reactive |
| Usage | Wraps a single value, accessed via .value | Wraps an object, accessed directly |
| Reactivity depth | Shallow for primitives, deep for objects inside | Deep reactivity for nested properties |
| Unwrapping in template | Automatically unwrapped | Automatically unwrapped |
| Best for | Simple values or single reactive variables | Complex state objects with multiple properties |
| Mutation | Change value via .value | Change properties directly |
Key Differences
ref creates a reactive container for a single value, such as a number, string, or even an object. You access or change the value inside a ref using the .value property. This makes it simple to track changes for individual variables.
On the other hand, reactive takes an entire object and makes all its properties reactive. You can read and write properties directly without needing .value. It deeply tracks nested properties, so changes inside nested objects are also reactive.
In templates, Vue automatically unwraps both ref and reactive values, so you can use them naturally. However, in JavaScript code, you must use .value for ref but not for reactive. This difference is important when writing logic.
Code Comparison
Here is how you create and update a simple counter using ref in Vue.
import { ref } from 'vue' export default { setup() { const count = ref(0) function increment() { count.value++ } return { count, increment } } }
Reactive Equivalent
Here is the same counter implemented using reactive with an object.
import { reactive } from 'vue' export default { setup() { const state = reactive({ count: 0 }) function increment() { state.count++ } return { state, increment } } }
When to Use Which
Choose ref when you need to track a single primitive value or want a simple reactive variable. It is lightweight and clear for individual pieces of state.
Choose reactive when managing complex state with multiple properties or nested objects. It allows direct property access and deep reactivity, making it easier to work with structured data.
In many cases, you can combine both: use reactive for objects and ref for standalone values inside your components.
Key Takeaways
ref wraps single values and requires .value to access in JS.reactive makes whole objects reactive with direct property access.ref for simple primitives and reactive for complex objects.