4 min read
•Question 24 of 37mediumWhat is shallowRef and shallowReactive?
Optimizing reactivity for large objects.
What You'll Learn
- shallowRef vs ref
- shallowReactive vs reactive
- When to use shallow versions
shallowRef
Only tracks .value changes, not deep mutations.
code.jsJavaScript
import { shallowRef } from 'vue'
const state = shallowRef({ count: 0 })
// Won't trigger update
state.value.count++
// Will trigger update
state.value = { count: 1 }shallowReactive
Only root-level properties are reactive.
code.jsJavaScript
import { shallowReactive } from 'vue'
const state = shallowReactive({
user: { name: 'John' },
count: 0
})
// Triggers update
state.count++
// Does NOT trigger update
state.user.name = 'Jane'When to Use
code.jsJavaScript
// Large immutable objects
const bigData = shallowRef(fetchedData)
// When replacing whole object
bigData.value = newFetchedData
// Integration with external libraries
const chart = shallowRef(null)
chart.value = new Chart(...)triggerRef for Manual Updates
code.jsJavaScript
import { shallowRef, triggerRef } from 'vue'
const state = shallowRef({ count: 0 })
state.value.count++
triggerRef(state) // Force update