JAVASCRIPT

Reactive Side Effects with Vue 3 watchEffect

Explore Vue 3's `watchEffect` to automatically re-run side effects whenever its reactive dependencies change, offering a simpler API for certain observation scenarios than `watch`.

<template>
  <div>
    <h1>watchEffect Example</h1>
    <p>Count: {{ count }}</p>
    <button @click="increment">Increment Count</button>

    <p>Message: {{ message }}</p>
    <input type="text" v-model="message" placeholder="Type here" />

    <p>Combined Effect Output:</p>
    <pre>{{ effectOutput }}</pre>
  </div>
</template>

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

const count = ref(0);
const message = ref('Hello Vue');
const effectOutput = ref('');

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

// watchEffect automatically tracks its dependencies
watchEffect(() => {
  const currentCount = count.value; // 'count' is tracked
  const currentMessage = message.value; // 'message' is tracked

  effectOutput.value = `Count is ${currentCount}, Message is "${currentMessage}".`;
  console.log(`Effect re-ran: Count=${currentCount}, Message="${currentMessage}"`);

  // An optional cleanup function can be returned
  // This runs before the effect re-runs and when the component unmounts
  return () => {
    console.log('Cleanup before next run or unmount');
  };
});

// Example of stopping a watchEffect manually
const stopWatch = watchEffect(() => {
  if (count.value >= 5) {
    console.log('Count reached 5, stopping watchEffect.');
    stopWatch(); // Stop this specific watchEffect
  }
});
</script>
How it works: This snippet demonstrates `watchEffect` in Vue 3, a utility for automatically running a side effect whenever any of its reactive dependencies change. Unlike `watch`, `watchEffect` doesn't require explicitly declaring dependencies; it automatically tracks any reactive data (like `ref`s or `reactive` objects) accessed during its first execution. It's ideal for scenarios where you want to perform actions based on multiple changing reactive states, such as logging, making API calls, or updating other reactive properties, without needing to specify `deep` or `immediate` options as often. It also shows how to provide a cleanup function and stop a watcher.

Need help integrating this into your project?

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

Hire DigitalCodeLabs