JAVASCRIPT
Managing Reactive State with ref and reactive in Vue 3
Learn how to effectively manage reactive data in your Vue 3 components using the `ref` and `reactive` functions from the Composition API for dynamic UI updates.
<template>
<div>
<h2>Counter: {{ count }}</h2>
<button @click="increment">Increment</button>
<h2>User Name: {{ user.name }}</h2>
<h2>User Age: {{ user.age }}</h2>
<button @click="updateUser">Update User</button>
</div>
</template>
<script setup>
import { ref, reactive } from 'vue';
// Using ref for primitive values (numbers, strings, booleans)
const count = ref(0);
function increment() {
count.value++; // Access value with .value
}
// Using reactive for objects and arrays
const user = reactive({
name: 'Alice',
age: 30
});
function updateUser() {
user.name = 'Bob';
user.age = 31;
}
</script>
How it works: This snippet demonstrates the two primary ways to declare reactive state in Vue 3's Composition API: `ref` and `reactive`. `ref` is used for primitive values (like numbers, strings, booleans) and requires accessing the value via the `.value` property. `reactive` is used for objects and arrays, automatically unwrapping nested `ref`s and providing deep reactivity without needing `.value` access. This distinction helps optimize reactivity and ensures UI updates efficiently.