JAVASCRIPT

Automatic Dependency Tracking with `watchEffect`

Discover `watchEffect` in Vue 3 for automatically re-running a side effect whenever its reactive dependencies change, simplifying reactive computations.

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

const userId = ref(1);
const userName = ref('');
const isLoading = ref(false);

// watchEffect runs immediately and re-runs whenever any reactive
// property accessed inside it changes.
watchEffect(async () => {
  isLoading.value = true;
  userName.value = 'Loading...';
  console.log(`Fetching user with ID: ${userId.value}`);

  // Simulate an API call
  await new Promise(resolve => setTimeout(resolve, 1000));
  const fetchedName = `User ${userId.value}`; // Mock data based on userId
  userName.value = fetchedName;
  isLoading.value = false;
  console.log(`Fetched user name: ${userName.value}`);
});

const incrementUserId = () => {
  userId.value++;
};
</script>

<template>
  <div>
    <h1>User Data Fetcher</h1>
    <p>Current User ID: {{ userId }}</p>
    <p>User Name: {{ isLoading ? 'Loading...' : userName }}</p>
    <button @click="incrementUserId">Next User</button>
  </div>
</template>
How it works: `watchEffect` is a powerful reactivity API in Vue 3 that automatically tracks the reactive dependencies accessed within its callback function. It runs immediately upon component setup and re-runs every time one of its tracked dependencies changes. This makes it ideal for performing side effects that depend on reactive state, such as data fetching or logging, without explicitly declaring dependencies like `watch`.

Need help integrating this into your project?

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

Hire DigitalCodeLabs