How Reactivity Works in Vue: Simple Explanation and Example
reactive or ref objects that track changes. When data changes, Vue automatically updates the parts of the UI that depend on that data, keeping everything in sync without manual DOM updates.Syntax
Vue uses reactive to make an object reactive and ref to make a single value reactive. The reactive function wraps an object so Vue can track its properties. The ref function wraps a primitive value or object and provides a .value property to access or update it.
import { reactive, ref } from 'vue'; const state = reactive({ count: 0 }); const message = ref('Hello'); // Access reactive object property console.log(state.count); // Access ref value console.log(message.value); // Update reactive object property state.count++; // Update ref value message.value = 'Hi';
Example
This example shows a simple Vue component that uses ref to create a reactive counter. When the button is clicked, the counter updates automatically in the UI without manual DOM changes.
<template>
<div>
<p>Count: {{ count }}</p>
<button @click="increment">Increment</button>
</div>
</template>
<script setup>
import { ref } from 'vue';
const count = ref(0);
function increment() {
count.value++;
}
</script>Common Pitfalls
One common mistake is trying to update a reactive ref value without using .value. Another is mutating a reactive object directly without using Vue's reactive APIs, which can cause changes not to be tracked.
Also, adding new properties to a reactive object after creation won't be reactive unless you use reactive or ref properly from the start.
import { ref, reactive } from 'vue'; // Wrong: updating ref without .value const count = ref(0); count = 1; // This does NOT update reactivity // Right: count.value = 1; // Wrong: adding new property to reactive object const state = reactive({ name: 'Vue' }); state.age = 3; // Not reactive // Right: define all reactive properties upfront const state2 = reactive({ name: 'Vue', age: 3 });
Quick Reference
| Concept | Usage | Notes |
|---|---|---|
| reactive | Wraps an object to make all properties reactive | Use for objects with multiple properties |
| ref | Wraps a single value or object, accessed via .value | Use for primitives or single reactive values |
| .value | Access or update the value inside a ref | Always use .value with ref |
| Tracking | Vue tracks dependencies automatically | No manual DOM updates needed |
| Limitations | Adding new properties after reactive creation is not tracked | Define all reactive properties upfront |