Vue.js & Composition API (50 Qs)•Part 1: Basic & Foundational Concepts (Junior / Entry-Level)
What is `watchEffect()` and how does it differ from `watch()`?
junior LevelCode ExampleSignals
In Simple Words:
watch(source, cb):- You must explicitly define what state to watch (
watch(userId, ...)). - Separates the watched dependency from the side effect.
- You must explicitly define what state to watch (
watchEffect(cb):- Runs immediately on initialization.
- Automatically tracks any reactive variables read inside the callback function.
- If you read
count.valueinsidewatchEffect, it automatically re-runs whenevercount.valuechanges.
typescript
// watch: Explicit dependency
watch(userId, async (newId) => {
userData.value = await fetchUser(newId);
});
// watchEffect: Automatic dependency tracking
watchEffect(async () => {
userData.value = await fetchUser(userId.value);
});