0
0
VueHow-ToBeginner · 3 min read

How to Use reactive in Vue 3: Simple Guide with Examples

In Vue 3, use the reactive function to create a reactive object that Vue tracks for changes. Wrap your state inside reactive(), and Vue will update the UI whenever the object's properties change.
📐

Syntax

The reactive function takes an object and returns a reactive proxy of that object. This proxy tracks changes to all nested properties.

  • reactive(object): Wraps the given object to make it reactive.
  • The returned object behaves like the original but triggers UI updates on changes.
javascript
import { reactive } from 'vue';

const state = reactive({
  count: 0,
  user: {
    name: 'Alice'
  }
});
💻

Example

This example shows a Vue component using reactive to create a state object. The UI updates automatically when the count changes.

vue
<template>
  <div>
    <p>Count: {{ state.count }}</p>
    <button @click="increment">Increase</button>
  </div>
</template>

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

const state = reactive({ count: 0 });

function increment() {
  state.count++;
}
</script>
Output
Count: 0 (initially) When clicking 'Increase', the count number increments by 1 each time.
⚠️

Common Pitfalls

One common mistake is trying to replace the entire reactive object directly, which breaks reactivity. Instead, update its properties.

Also, reactive only works with objects, not primitives like numbers or strings. Use ref for primitives.

javascript
import { reactive } from 'vue';

const state = reactive({ count: 0 });

// Wrong: replacing the whole object breaks reactivity
// state = { count: 1 }; // This will not update the UI

// Right: update properties inside the reactive object
state.count = 1;
📊

Quick Reference

  • Use reactive(object) for reactive state with multiple properties.
  • Use ref(value) for single primitive values.
  • Update properties inside reactive objects to keep reactivity.
  • Access reactive properties directly in templates.

Key Takeaways

Use reactive to create reactive objects that Vue tracks deeply.
Always update properties inside reactive objects, not replace the whole object.
reactive works only with objects; use ref for primitives.
Reactive state updates automatically reflect in the Vue template.
Import reactive from 'vue' and use it inside setup() or <script setup>.