10

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?

Alex Balashov
  • 3,218
  • 4
  • 27
  • 36
  • If you pass an Array (hence, an Object) to `ref`, [it will be converted to a `reactive`](https://github.com/vuejs/vue-next/blob/master/packages/reactivity/src/ref.ts#L31), so making it a `reactive` right away makes more sense. Note: the `isObject` method used for the check in the previous link [uses `typeof x === "object"`](https://github.com/vuejs/vue-next/blob/master/packages/shared/src/index.ts#L71), which the case for an Array – blex Dec 18 '20 at 17:45
  • 2
    Are you sure about that? I just checked by creating a `ref([])` in a `setup()` function; `isReactive(x)` returns `false`, while `isRef(x)` returns `true`. – Alex Balashov Dec 18 '20 at 18:45
  • This question is actually comprehensively answered (including for arrays) here: https://stackoverflow.com/a/65262638/645016 – sxc731 Jun 28 '23 at 14:50

2 Answers2

-1

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.

-2

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.

Xinchao
  • 2,929
  • 1
  • 24
  • 39