What does shallowRef() do?
shallowRef() is a variant of ref() that makes only the value itself reactive, but does NOT make the contents of an object reactive when the value is an object, array, or any complex structure.
In simple terms:
shallowRef()tracks only changes to.value, but does not watch the object's internal properties.
This is shallow reactivity.
How shallowRef() works
import { shallowRef } from 'vue'
const state = shallowRef({ count: 0 })What is tracked:
- changes to
state.valueitself
What is NOT tracked:
state.value.count++(Vue will not see this change)
Example
const obj = shallowRef({ n: 1 })
obj.value.n++ // UI does NOT update
obj.value = { n: 2 } // UI updatesWhy?
shallowRefreacts only to replacingvalue- not to changes inside the object
When to use shallowRef?
1. For large objects where deep reactivity is not needed
For example, if the object contains 100,000 elements or heavy structures:
const hugeData = shallowRef(veryBigObject)This saves memory and speeds up performance.
2. When working with DOM elements
const el = shallowRef(null)The DOM should not be reactive.
ref() will try to make it reactive, which is unnecessary.
shallowRef() is ideal.
3. For third-party libraries and class instances
For example, maps, charts, editors:
const chart = shallowRef(null)Because Chart.js, Leaflet, Three.js objects should not be reactive.
4. When you want to control updates yourself
Then use triggerRef():
import { shallowRef, triggerRef } from 'vue'
const data = shallowRef({ count: 0 })
data.value.count++
triggerRef(data) // manually update the UIshallowRef vs ref (an important difference)
| Feature | ref | shallowRef |
|---|---|---|
| tracks nested properties | yes | no |
| deep reactivity | yes | no |
| suited for objects | yes | if deep reactivity isn't needed |
| re-renders on every nested update | yes | no |
| re-renders only when value is replaced | no | yes |
An example where ref is worse than shallowRef
A third-party library:
const editor = ref(new CodeMirror(...))Vue will try to make the editor fully reactive. This:
- slows things down
- creates strange bugs
- increases memory usage
The correct approach:
const editor = shallowRef(null)Summary (great for an interview)
shallowRef()creates a shallow reactive ref. Vue tracks only changes to.value, not the nested properties. It is used for DOM elements, large objects, class instances, third-party library objects, and cases where deep reactivity is not needed.
Short Answer
Interview readyA concise answer to help you respond confidently on this topic during an interview.