Performance: Watch and watchEffect
This concept affects how reactive data changes trigger component updates and side effects, impacting interaction responsiveness and rendering speed.
watch(() => reactiveProperty, () => { lightComputation(); });watch(() => largeReactiveObject, () => { heavyComputation(); }, { deep: true });| Pattern | DOM Operations | Reflows | Paint Cost | Verdict |
|---|---|---|---|---|
| Deep watch on large object | Many DOM updates | Multiple reflows per change | High paint cost | [X] Bad |
| Watch specific reactive property | Minimal DOM updates | Single reflow per change | Low paint cost | [OK] Good |
| watchEffect with heavy computation | DOM updates blocked | Reflows delayed | High paint cost | [X] Bad |
| watchEffect with conditional light work | Minimal DOM updates | Single reflow | Low paint cost | [OK] Good |
watch and watchEffect in Vue?watch behaviorwatch listens to specific reactive data sources you specify and runs a callback only when those change.watchEffect behaviorwatchEffect runs immediately and tracks all reactive data accessed inside it, rerunning whenever any of those change.watch tracks specific reactive sources, watchEffect tracks all reactive dependencies automatically. -> Option Bwatch tracks specific reactive sources, watchEffect tracks all reactive dependencies automatically. [OK]count in Vue 3 Composition API?watch accepts a ref directly as the first argument, which automatically watches its .value.newVal and oldVal as parameters, correctly used in watch(count, (newVal, oldVal) => { console.log(newVal) }) to log the new value.count.value = 2 is executed?import { ref, watch } from 'vue'
const count = ref(1)
watch(() => count.value, (newVal, oldVal) => {
console.log(`Changed from ${oldVal} to ${newVal}`)
})
count.value = 2watch? How to fix it?import { ref, watch } from 'vue'
const count = ref(0)
watch(count, (newVal) => {
console.log(newVal)
})watch(count, callback) is valid; it automatically tracks count.value changes.newVal and optional oldVal; omitting oldVal is fine.watchEffect runs immediately and tracks all reactive dependencies automatically.watchEffect returns a stop function that can be called to stop the effect manually.watchEffect and store the returned stop function to call later -> Option CwatchEffect and store the returned stop function to call later [OK]Pass the test and this pattern moves unknown