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?
import { ref } from 'vue'
const count = ref(0)This creates an object:
{
value: 0 // reactive property
}How do you work with it?
Reading:
console.log(count.value)Changing:
count.value++Vue automatically tracks the change and updates the DOM.
Example in a component
<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:
<p>{{ message }}</p> <!-- works -->What types of data is ref() used for?
Primitives
(mandatory!)
const count = ref(0)
const name = ref('Alex')
const isVisible = ref(true)DOM elements (template refs)
<input ref="inputEl">const inputEl = ref(null)Objects, when you need the ability to replace the whole object
const user = ref({ name: 'Alex' })
user.value = { name: 'John' } // can be replaced entirelyHow does ref() differ from reactive()?
| ref | reactive |
|---|---|
| for primitives | for objects |
stored in .value | works like a plain object |
| can be replaced entirely | cannot be replaced (loses reactivity) |
| works with both primitives and objects | only objects, arrays, Map, Set |
Automatic wrapping/unwrapping of ref
In a template:
<p>{{ count }}</p> <!-- without .value -->When destructuring:
Not allowed:
const { count } = form // loses reactivityCorrect:
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.valueproperty. 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 readyA concise answer to help you respond confidently on this topic during an interview.