Vue - Choosing Between Ref and Reactive

  • Frontend
  • 25 Nov, 2023

In Vue 3, ref and reactive are two common ways to declare reactive data.

When I started learning Vue 3, I was told that ref is typically used for primitives like numbers or strings, while reactive is better for complex object data like objects or arrays.

But in my real experience with Vue 3, I found that in certain situations, it’s still recommended to use ref instead of reactive even for object types.

The basic usage of ref and reactive:

// ref()
const a = ref(1)
a.value++
console.log(a.value) //2

const refObj = ref({ count: 1 })
refObj.value.count++
console.log(refObj.value.count) //2

// reactive()
const reactiveObj = reactive({
  count: 1,
})
reactiveObj.count++
console.log(reactiveObj.count) //2

As we can see, the good thing about using reactive is that you don’t have to unwrap the object manually. This means you can use it directly without needing to call .value.

The advantage of using Ref()

From the official doc, we learn that:

  • ref can hold any type of value, including deeply nested objects and arrays. ref makes its value deeply responsive. This means that even if there are changes in nested objects or arrays, the changes will be detected.

  • ref is invoking reactive behind the scenes. The system automatically converts it based on the value we pass into ref: ref(xx) → reactive({value: xx})

    That’s why when using ref in a script, we have to access the value using .value.

Limitation of Reactive()

A few cons of using reactive:

❌ Limited to object types only

❌ Reactivity loss with ES6 destructuring

❌ Difficult to distinguish between reactive and regular objects visually

❌ Not dev-friendly when replacing the entire object

//After running this code, the object loses its original reactivity
let b = reactive({})
b = {}

I believe the last point is the main limitation of using reactive. When you need to set an object or array to empty, you’ll need to find a workaround. However, with ref, you can directly address this by assigning {} or [] to the value without losing reactivity.

Conclusion

  • It’s preferable to use ref when you need to reassign an array or object
  • Both ref and reactive are suitable for nested arrays or objects, depending on preference
  • As per official documentation, using ref is recommended for declaring reactive states
Tags :