JAVASCRIPT

Managing Reactive Side Effects with Vue 3's `watchEffect`

Learn to use `watchEffect` in Vue 3 to automatically re-run a function whenever its reactive dependencies change, providing a simpler alternative to `watch` for certain scenarios.

// src/components/WatchEffectExample.vue
<template>
  <div>
    <h2>WatchEffect Example</h2>
    <p>Count: {{ count }}</p>
    <p>Multiplier: {{ multiplier }}</p>
    <p>Result: {{ result }}</p>
    <button @click="increment">Increment Count</button>
    <button @click="changeMultiplier">Change Multiplier</button>
    <p>Console will log when `count` or `multiplier` changes.</p>
  </div>
</template>

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

const count = ref(0);
const multiplier = ref(2);

const result = computed(() => count.value * multiplier.value);

// watchEffect will automatically track count and multiplier
watchEffect(() => {
  console.log(`Current Count: ${count.value}, Current Multiplier: ${multiplier.value}, Current Result: ${result.value}`);
  // Any reactive property accessed here will be tracked
  // If result.value was not needed for logging, it would not be tracked automatically.
});

const increment = () => {
  count.value++;
};

const changeMultiplier = () => {
  multiplier.value = multiplier.value === 2 ? 3 : 2;
};

// Example of stopping watchEffect
// const stopWatchEffect = watchEffect(() => {
//   console.log('This effect will stop after 5 seconds');
// });
// setTimeout(() => {
//   stopWatchEffect();
//   console.log('watchEffect has been stopped.');
// }, 5000);
</script>

// src/App.vue
<template>
  <WatchEffectExample />
</template>

<script setup>
import WatchEffectExample from './components/WatchEffectExample.vue';
</script>
How it works: This snippet demonstrates `watchEffect`, a reactive primitive in Vue 3 that automatically tracks its dependencies and re-runs its side effect function whenever any of those dependencies change. Unlike `watch`, you don't explicitly list dependencies; `watchEffect` infers them from the reactive properties accessed within its callback. Here, it logs the `count`, `multiplier`, and `result` whenever `count` or `multiplier` is updated, showcasing its ability to react to multiple sources and a computed property. It's ideal for effects that don't need access to the old value of a dependency.

Need help integrating this into your project?

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

Hire DigitalCodeLabs