Vue 3 Ref

Posted on  by admin
reactive() only takes objects, NOT JS primitives (String, Boolean, Number, BigInt, Symbol, null, undefined).

ref() is calling reactive() behind the scenes. Since reactive() works for objects and ref() calls reactive(), objects work for both. BUT, ref() has a .value property for reassigning, reactive() does not have this and therefore CANNOT be reassigned. it's a primitive (for example 'string', true, 23, etc).

Ref vs Reactive :

it's an object you need to later reassign (like an array - more info here). reactive() when..

it's an object you don't need to reassign, and you want to avoid the overhead of ref(). ref() seems like the way to go since it supports all object types and allows reassigning with .value. ref() is a good place to start, but as you get used to the API, know that reactive() has less overhead, and you may find it better meets your needs.

You'll always use ref() for primitives, but ref() is good for objects that need to be reassigned, like an array. The above with reactive() would require reassigning a property instead of the whole object.

A good use-case for reactive() is a group of primitives that belong together:. the code above feels more logical than. If you're still lost, this simple guide helped me: https://www.danvega.dev/blog/2020/02/12/vue3-ref-vs-reactive/.

Ref :

An argument for only ever using ref(): https://dev.to/ycmjason/thought-on-vue-3-composition-api-reactive-considered-harmful-j8c. The decision-making behind why reactive() and ref() exist as they do and other great information, the Vue Composition API RFC: https://vue-composition-api-rfc.netlify.app/#overhead-of-introducing-refs.

There are some similarities between ref and reactive, in that they both provide a method to store data and allow that data to be reactive.

Dynamic $refs in v-for

High level differences:. You can’t use reactive() on primitives (strings, numbers, booleans) - that’s what you need refs for, because you will have situations where you need to have a “reactive boolean”, for example….

of course your can create an object that wraps the primitive value and make that reactive():. and just like that, you reinvented a ref. Source: Vue forum discussion. reactive takes the object and returns a reactive proxy to the original object. In the above, Whenever we want to change or access the properties of page,say page.ads, page.filteredAds will update via Proxies.