JAVASCRIPT

Vue 3 Composition API: State Management with `ref` and `reactive`

Learn to manage component state in Vue 3 using the Composition API's `ref` for primitive values and `reactive` for objects, a fundamental pattern.

<template>
  <div>
    <p>Count (ref): {{ count }}</p>
    <button @click="incrementRef">Increment Ref</button>

    <p>User Name (reactive): {{ user.name }}</p>
    <p>User Age (reactive): {{ user.age }}</p>
    <button @click="updateReactive">Update Reactive</button>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue';

// Using ref for primitive values (numbers, strings, booleans)
const count = ref(0);
const incrementRef = () => {
  count.value++; // Access with .value
};

// Using reactive for objects and arrays
const user = reactive({
  name: 'Alice',
  age: 30
});

const updateReactive = () => {
  user.name = 'Bob';
  user.age++;
};
</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, and booleans, requiring you to access and modify its value via the `.value` property. `reactive` is used for objects and arrays, creating a reactive proxy that allows direct property access and modification without `.value`. Both ensure that changes automatically trigger re-renders in the component.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs