Vue.js Developer interview question · Most asked
computed, watch or watchEffect: when do you use each?
Summary
computed derives a value from reactive state and caches it until its dependencies change; use it for anything you would display or pass on. watch runs a side effect when specific sources change, with access to old and new values. watchEffect runs a side effect immediately and re-runs whenever any reactive value it read changes.
Longer Answer
Rules of thumb:
- Deriving data:
computed, never a watcher that writes to another ref. - Side effects (fetching, writing to localStorage, calling an API) in response to changes:
watchwith explicit sources (clear intent, lazy by default,immediate/deep/onceoptions). - Quick effects whose dependencies are obvious from the code:
watchEffect.
Computed getters must be pure. Watchers that fetch data should handle races: onWatcherCleanup (3.5+) or the onCleanup argument lets you abort the previous request when the source changes again.
Code Example
const fullName = computed(() => `${first.value} ${last.value}`);
watch(query, async (q, _old, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort());
results.value = await search(q, { signal: controller.signal });
});
Key Points
- computed: cached derived values, pure.
- watch: explicit sources, old/new values.
- watchEffect: auto-tracked, runs immediately.
- Clean up async work in watchers.
More most-asked Vue.js Developer questions
- How do you use Vue Router: dynamic routes, nested routes and navigation guards?
- What are composables, and why did they replace mixins?
- How does Vue 3's reactivity system work, and how does it differ from Vue 2's?
- Options API or Composition API: what is the difference, and which would you use?
- ref or reactive: what is the difference, and when do you use each?
- Why does v-for need a key, and why should it not be the index?
- How do props work, and what is one-way data flow?
- Pinia or Vuex: what is the difference, and why is Pinia now recommended?