0
0
Vueframework~5 mins

Why advanced reactivity matters in Vue

Choose your learning style9 modes available
Introduction

Advanced reactivity helps your app update only what needs to change. This makes your app faster and smoother.

When your app has many parts that change based on user actions
When you want to avoid slow updates and keep the app feeling quick
When you need to track changes deeply inside objects or arrays
When you want to write less code but still keep UI in sync
When building complex interfaces that depend on many data points
Syntax
Vue
import { reactive, ref, computed, watch } from 'vue';

const state = reactive({ count: 0 });
const doubled = computed(() => state.count * 2);

watch(() => state.count, (newVal, oldVal) => {
  console.log(`Count changed from ${oldVal} to ${newVal}`);
});

reactive makes an object reactive so Vue tracks its changes.

computed creates a value that updates automatically when dependencies change.

Examples
Using ref for a simple reactive number.
Vue
const count = ref(0);

function increment() {
  count.value++;
}
Using reactive for an object so Vue tracks changes inside it.
Vue
const state = reactive({ name: 'Alice', age: 30 });

state.age = 31;
computed automatically updates when count changes.
Vue
const doubled = computed(() => count.value * 2);
watch runs code when a reactive value changes.
Vue
watch(() => state.age, (newAge, oldAge) => {
  console.log(`Age changed from ${oldAge} to ${newAge}`);
});
Sample Program

This Vue component shows a count and its doubled value. When you click the button, the count increases and the doubled value updates automatically thanks to reactivity.

Vue
<template>
  <div>
    <p>Count: {{ count }}</p>
    <p>Doubled: {{ doubled }}</p>
    <button @click="increment">Add 1</button>
  </div>
</template>

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

const count = ref(0);
const doubled = computed(() => count.value * 2);

function increment() {
  count.value++;
}
</script>
OutputSuccess
Important Notes

Advanced reactivity helps avoid updating the whole page, only the parts that changed.

Using ref and reactive properly keeps your code clean and efficient.

Watchers let you react to changes for side effects like logging or fetching data.

Summary

Advanced reactivity keeps your app fast by updating only what changes.

Use ref, reactive, computed, and watch to manage reactive data.

This makes your app easier to build and maintain.