Skip to main content

What is ref()?

ref() is a function from the Composition API (Vue 3) that creates a reactive wrapper around a value of any type and lets Vue track its changes.

In simple terms:

ref() makes a value reactive. For primitives (string, number, boolean) this is the only way to make them "live" in the Composition API.

This is one of the key reactivity tools in Vue 3.


What does a ref look like?

js
import { ref } from 'vue' const count = ref(0)

This creates an object:

js
{ value: 0 // reactive property }

How do you work with it?

Reading:

js
console.log(count.value)

Changing:

js
count.value++

Vue automatically tracks the change and updates the DOM.


Example in a component

vue
<script setup> import { ref } from 'vue' const message = ref('Hello') function update() { message.value = 'Updated!' } </script> <template> <p>{{ message }}</p> <button @click="update">Change</button> </template>

Why is .value needed?

Because a ref is an object, and the reactive property is stored under the value key.

But in templates, .value is not needed, Vue automatically "unwraps" it:

html
<p>{{ message }}</p> <!-- works -->

What types of data is ref() used for?

Primitives

(mandatory!)

js
const count = ref(0) const name = ref('Alex') const isVisible = ref(true)

DOM elements (template refs)

html
<input ref="inputEl">
js
const inputEl = ref(null)

Objects, when you need the ability to replace the whole object

js
const user = ref({ name: 'Alex' }) user.value = { name: 'John' } // can be replaced entirely

How does ref() differ from reactive()?

refreactive
for primitivesfor objects
stored in .valueworks like a plain object
can be replaced entirelycannot be replaced (loses reactivity)
works with both primitives and objectsonly objects, arrays, Map, Set

Automatic wrapping/unwrapping of ref

In a template:

html
<p>{{ count }}</p> <!-- without .value -->

When destructuring:

Not allowed:

js
const { count } = form // loses reactivity

Correct:

js
import { toRefs } from 'vue' const { count } = toRefs(form)

Important nuances

1. You can always mutate .value

This triggers a UI update.

2. You can replace the ref with a new object

(a ref can be overwritten entirely).

3. A ref inside an object automatically becomes reactive

Vue creates a proxy wrapper.


Summary (great for an interview)

ref() is a Composition API function that creates a reactive value. It stores the value in the .value property. It is mandatory for primitives in the Composition API. It is used for data, DOM elements, and any values that need to react to changes.

Short Answer

Interview ready
Premium

A concise answer to help you respond confidently on this topic during an interview.