Ref() vs Reactive() in Vue 3 — what’s the right choice?
Composition API comes with two ways to introduce a reactive state into the components. Thus you’ll face the decision of whether to use ref, reactive or both. I will help you to make the right choice, but let’s start with a quick introduction to both.
Quick introduction
Ref()
and reactive()
are used to track changes of its argument. When using them to initialize variables you give Vue information: “Hey, I want you to re-build or re-evaluate everything that depends on those variables every time they change”.
In the example below both personRef
and personReactive
will change its name after clicking the button, but person
which is just a normal JS object will not.
Basically, they are used to make your components reactive (react to changes).
Differences
There are three main differences that you should be aware of:
ref()
can take as arguments primitives (most common:Boolean
,String
andNumber
) as well as Objects, while…