Skip to main content

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

js
import { shallowRef } from 'vue' const state = shallowRef({ count: 0 })

What is tracked:

  • changes to state.value itself

What is NOT tracked:

  • state.value.count++ (Vue will not see this change)

Example

js
const obj = shallowRef({ n: 1 }) obj.value.n++ // UI does NOT update obj.value = { n: 2 } // UI updates

Why?

  • shallowRef reacts only to replacing value
  • 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:

js
const hugeData = shallowRef(veryBigObject)

This saves memory and speeds up performance.


2. When working with DOM elements

js
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:

js
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():

js
import { shallowRef, triggerRef } from 'vue' const data = shallowRef({ count: 0 }) data.value.count++ triggerRef(data) // manually update the UI

shallowRef vs ref (an important difference)

FeaturerefshallowRef
tracks nested propertiesyesno
deep reactivityyesno
suited for objectsyesif deep reactivity isn't needed
re-renders on every nested updateyesno
re-renders only when value is replacednoyes

An example where ref is worse than shallowRef

A third-party library:

js
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:

js
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 ready
Premium

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