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: watch with explicit sources (clear intent, lazy by default, immediate / deep / once options).
  • 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

← All Vue.js Developer questions