Skip to content

Reactivity Fundamental

Vue’s reactivity system automatically keeps your UI in sync with your data. This section covers how to declare reactive state, use refs and reactive objects, and best practices for managing state in Vue components.

The recommended way to declare reactive state in the Composition API is with the ref() function:

import { ref } from 'vue'
const count = ref(0)

ref() returns a reactive object with a .value property. In templates, refs are automatically unwrapped:

// Example Vue SFC (for illustration only)
// <template>
// <button @click="count++">{{ count }}</button>
// </template>
// <script setup>
import { ref } from 'vue'
const count = ref(0)
// </script>

For objects, use reactive() to make the entire object reactive:

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

In templates:

<button @click="state.count++">{{ state.count }}</button>

Refs and reactive objects allow Vue to track dependencies and update the DOM efficiently. Use refs for primitives and reactive for objects/arrays.

Reactive objects are deeply reactive, so nested properties are tracked:

const obj = ref({ nested: { count: 0 } })
obj.value.nested.count++

DOM updates are batched and applied asynchronously. Use nextTick() to wait for the DOM update:

import { nextTick } from 'vue'
await nextTick()
  • Use ref() for primitives, reactive() for objects.
  • Avoid destructuring reactive objects to keep reactivity.
  • Use composables to share stateful logic.