Reactivity Fundamentals
1/1/2025
Reactivity Fundamentals
One of Vue’s most distinctive features is the unobtrusive reactivity system. Component state consists of reactive JavaScript objects.
Declaring Reactive State
With the Composition API, the recommended way to declare reactive state is using the ref() function:
javascript
import { ref } from 'vue'
const count = ref(0)Why Refs?
You might be wondering why we need refs with the .value instead of plain variables. To explain that, we need to briefly discuss how Vue’s reactivity system works.
Deep Reactivity
Refs can hold any value type, including deeply nested objects, arrays, or JavaScript built-in data structures like Map.
javascript
import { ref } from 'vue'
const obj = ref({
nested: { count: 0 },
arr: ['foo', 'bar']
})
function mutateDeeply() {
obj.value.nested.count++
obj.value.arr.push('baz')
}Using reactive()
There is another way to declare reactive state, with the reactive() API:
javascript
import { reactive } from 'vue'
const state = reactive({ count: 0 })Computed Properties
Computed properties are cached based on their reactive dependencies:
javascript
import { ref, computed } from 'vue'
const count = ref(0)
const doubled = computed(() => count.value * 2)
Monkey Knows Wiki