Vue JS Vue JS Reactivity System 2 — Questions and Answers
Question 1: What Vue 3 function lets you run a side effect whenever its reactive dependencies change?
- computed()
- watch()
- watchEffect() (Correct answer)
- onMounted()
Correct answer: watchEffect()
watchEffect() immediately runs a function and automatically re-runs it whenever any reactive dependency accessed inside it changes.
Question 2: What is the key difference between watch() and watchEffect() in Vue 3?
- watch() is synchronous; watchEffect() is async
- watch() requires explicit source declaration; watchEffect() auto-tracks dependencies (Correct answer)
- watch() cannot access old values; watchEffect() can
- watch() runs immediately on mount; watchEffect() does not
Correct answer: watch() requires explicit source declaration; watchEffect() auto-tracks dependencies
watch() observes specific declared sources and provides old/new values, while watchEffect() auto-collects dependencies at runtime.
Question 3: How do you stop a watcher created inside setup() from running?
- Call the stop function returned by watch()/watchEffect() (Correct answer)
- Set the source ref to null
- Use onUnmounted() with clearWatch()
- Watchers cannot be manually stopped
Correct answer: Call the stop function returned by watch()/watchEffect()
watch() and watchEffect() both return a stop function that, when called, removes the watcher.
Question 4: Which option in watch() makes it run immediately on component mount in addition to when the source changes?
- eager: true
- immediate: true (Correct answer)
- once: true
- sync: true
Correct answer: immediate: true
The immediate: true option causes the watcher callback to execute right away with the current value before any change occurs.
Question 5: What does the deep: true option do in a Vue 3 watch() call?
- Enables async watchers
- Forces the watcher to track nested object property changes (Correct answer)
- Creates a computed watcher
- Runs the watcher synchronously
Correct answer: Forces the watcher to track nested object property changes
deep: true causes Vue to traverse every nested property of the source object so changes at any depth trigger the callback.
Question 6: In Vue 3's Composition API, which function creates a read-only reactive reference derived from other reactive state?
- ref()
- reactive()
- computed() (Correct answer)
- readonly()
Correct answer: computed()
computed() accepts a getter function and returns a cached, read-only reactive ref that only re-evaluates when its dependencies change.
What Vue 3 function lets you run a side effect whenever its reactive dependencies change?