computed vs watch vs watchEffect: when do you use each?
computed
A derived value cached until one of its reactive dependencies changes. Use it whenever a value can be calculated from other state: filtered lists, totals, formatted strings. Getters must be pure (no side effects, no async). Writable computeds take get and set.
watch
Runs a side effect when specific sources change. Gives old and new values. Lazy by default (does not run immediately).
- Sources: a ref, a getter
() => props.id, a reactive object, or an array of them. - Options:
{ immediate: true },{ deep: true }(or a depth number in 3.5),{ once: true },flush: 'post'to run after the DOM updates. - Use for: fetching data when an id changes, saving to localStorage, calling a non-Vue API.
watchEffect
Runs immediately and tracks automatically whatever it reads, re-running when any of it changes. No old value. Convenient when the dependencies are obvious from the code.
Cleanup
Both receive an onCleanup callback (or use onWatcherCleanup() in Vue 3.5) to cancel the previous request when the source changes quickly, which prevents race conditions. Watchers created synchronously in setup stop automatically on unmount.
Example
<script setup>
import { ref, computed, watch } from 'vue';
const props = defineProps({ userId: Number });
const items = ref([{ price: 10, qty: 2 }, { price: 5, qty: 1 }]);
const total = computed(() => items.value.reduce((sum, i) => sum + i.price * i.qty, 0));
const user = ref(null);
watch(
() => props.userId,
async (id, _oldId, onCleanup) => {
const controller = new AbortController();
onCleanup(() => controller.abort()); // cancel the stale request
const res = await fetch(`/api/users/${id}`, { signal: controller.signal });
user.value = await res.json();
},
{ immediate: true },
);
const theme = ref(localStorage.getItem('theme') ?? 'light');
watch(theme, value => localStorage.setItem('theme', value));
</script>Follow-up questions interviewers ask
Try answering each one before you open it.
What is the most common misuse of watch?
Using a watcher to keep one piece of state in sync with another (watch(a, v => b.value = v * 2)). That should be a computed: it is cached, always consistent and needs no extra update cycle.