QA
Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?

❓ Interview Prompt: Compare computed, methods, watch, and watchEffect regarding caching, return values, and side effects.

Computed Properties ('computed(() => ...)'):

•
Cached based on their reactive dependencies. Only re-evaluate when a dependency changes.
•
Must be pure (no side effects like network requests or DOM mutations).
•
Must return a value. Used for transforming or filtering data for the template.

Methods (regular functions):

•
Not cached. Executed every time a component re-renders or when triggered by an event handler.

Watchers ('watch' / 'watchEffect'):

•
Used for side effects (fetching data, saving to localStorage, triggering animations) in response to reactive state changes.
•
'watch(source, callback)': Explicitly watch specific refs/reactive objects. Gives access to '(newValue, oldValue)'.
•
'watchEffect(callback)': Automatically tracks any reactive property read inside the callback and runs immediately on mount.

Code Implementation Example

javascript
import { ref, computed, watch, watchEffect } from 'vue';

const firstName = ref('Alice');
const lastName = ref('Smith');

// 1. Computed: Cached, pure transformation
const fullName = computed(() => `${firstName.value} ${lastName.value}`);

// 2. watch: Explicit dependency, side effect on change
watch(fullName, (newVal, oldVal) => {
  console.log(`Name changed from ${oldVal} to ${newVal}`);
  localStorage.setItem('user_name', newVal); // Side effect!
});

// 3. watchEffect: Auto-tracks dependencies, runs immediately
watchEffect(() => {
  console.log('Current full name:', firstName.value, lastName.value);
});
💡computed caching vs watch and watchEffect side effect handling.
🎯 Interview Key Takeaway

Use computed for cached data transformations. Use watch/watchEffect for asynchronous or DOM side effects.

#computed#watch#watchEffect#Beginner
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between v-if and v-show and when should you use each?