Vue 3 composition API - ref() vs reactive() for arrays

Viewed 3379

The guidance in Vue 3 documentation and in folk literature is that ref() is for scalars and primitives, while reactive() is for Objects.

However, in JavaScript, arrays are a special case of Object. Notwithstanding issues such as monitoring nested object elements for new property additions and other wrinkles, is there a best practice on whether to handle arrays as ref or reactive, whether from a performance perspective or any other?

2 Answers

I would use ref for primitive values as you already mentioned. For object type (objects or Arrays), I would advice to use the reactive property. This makes your code easier to read and removes the ".value" you would have to add when using the ref property.

I would say, only use ref when you cannot use reactive. In your template they are pretty much the same because ref is automatically unwrapped. But in your code you have to remember that anything you created with ref will be a Ref - you need to manually unwrap it by calling .value, for most of the time.

You can ref around arrays and objects, but you still need to call .value afterwards. ref(x) does not "upgrade" automatically to reactive(x) just because x is an object (even though internally ref(object) might be calling reactive at some point).

There are a few cases when you don't need to manually unwrap, e.g. if you assign your ref to a property of a reactive object. But this is actually what makes it confusing and error-prone.

Btw if you use typescript, reactive around primitives will report error right away and that is the time you know you need to use ref.

Related