JAVASCRIPT
Understanding Vue 3 Reactivity with `ref` and `reactive`
Learn the core differences and best practices for managing reactive state in Vue 3 using `ref` for primitives and `reactive` for objects, ensuring your UI updates automatically.
<script setup>
import { ref, reactive, toRefs } from 'vue';
// Using ref for primitive values and single objects
const count = ref(0);
const message = ref('Hello Vue 3!');
const userRef = ref({ name: 'Alice', age: 30 });
const increment = () => {
count.value++; // Access .value inside <script setup>
};
// Using reactive for objects
const state = reactive({
firstName: 'Bob',
lastName: 'Smith',
details: {
occupation: 'Developer',
company: 'Acme Inc.'
}
});
const changeName = () => {
state.firstName = 'Robert'; // Direct access for reactive objects
};
// Unwrapping reactive properties with toRefs (useful for destructuring)
const { firstName, lastName } = toRefs(state);
firstName.value = 'Bobby'; // Use .value after toRefs
// Reactivity works directly in the template without .value
</script>
<template>
<div>
<h2>Ref Example</h2>
<p>Count: {{ count }}</p>
<p>Message: {{ message }}</p>
<p>User Ref: {{ userRef.name }} ({{ userRef.age }})</p>
<button @click="increment">Increment Count</button>
<h2>Reactive Example</h2>
<p>Name: {{ state.firstName }} {{ state.lastName }}</p>
<p>Occupation: {{ state.details.occupation }}</p>
<button @click="changeName">Change First Name (Reactive)</button>
<h2>toRefs Example</h2>
<p>Destructured First Name: {{ firstName }}</p>
</div>
</template>
How it works: This snippet demonstrates the fundamental reactivity APIs in Vue 3: `ref` and `reactive`. `ref` is used for creating reactive references to primitive values (like numbers, strings) or single objects, requiring `.value` to access/mutate their content in JavaScript, but not in the template. `reactive` is used for creating reactive objects directly, where properties are accessed and mutated directly without `.value`. The `toRefs` utility is shown for safely destructuring properties from a `reactive` object while retaining their reactivity.