Sobes.tech
Middle+

Tell me about watch and watchEffect in Vue 3, computed properties. How to remove a watcher?

sobes.tech AI

Answer from AI

In Vue 3, there are several ways to reactively track data changes: watch, watchEffect, and computed.

  • watch — allows monitoring specific reactive sources (e.g., ref or reactive) and executing a handler function when they change. It is used when you need to react to data changes asynchronously or perform side effects.

    import { ref, watch } from 'vue';
    const count = ref(0);
    const stop = watch(count, (newVal, oldVal) => {
      console.log(`count changed from ${oldVal} to ${newVal}`);
    });
    
    // To remove the watcher:
    stop();
    
  • watchEffect — automatically tracks all reactive dependencies used inside its function and reruns it when they change. It is convenient for reactive side effects without explicitly specifying dependencies.

    import { ref, watchEffect } from 'vue';
    const count = ref(0);
    const stop = watchEffect(() => {
      console.log(`count is now: ${count.value}`);
    });
    
    // To stop watching:
    stop();
    
  • computed — a computed property that caches its result and automatically updates when its reactive dependencies change. It is used for deriving values based on reactive data.

    import { ref, computed } from 'vue';
    const count = ref(1);
    const double = computed(() => count.value * 2);
    console.log(double.value); // 2
    

Removing a watcher: When creating a watcher via watch or watchEffect, a stop function is returned, which, when called, stops the observation and releases resources.

Tell me about watch and watchEffect in Vue 3… - sobes.tech