javascript / expert
Snippet
Debugging Reactivity via onTrack and onTrigger
Vue's watchEffect (and watch) accept an options object with onTrack and onTrigger hooks. These are essential for expert-level performance auditing and debugging. onTrack runs when a reactive dependency is first accessed within the effect, while onTrigger runs when a mutation causes the effect to re-run. This allows developers to pinpoint exactly why an expensive computation is executing.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { watchEffect, ref } from 'vue';const count = ref(0);watchEffect(() => console.log('Current count:', count.value),{onTrack(e) {// Triggered when count.value is tracked as a dependencyconsole.log('Dependency tracked:', e.key);},onTrigger(e) {// Triggered when count.value mutation triggers the effectconsole.log('Effect triggered by:', e.type, 'on', e.key);debugger;}});
vue
Breakdown
1
onTrack(e) {
Lifecycle hook that fires when a reactive property is collected as a dependency for the first time.
2
onTrigger(e) {
Lifecycle hook that fires exactly before the effect is re-executed due to a dependency change.
3
debugger;
Pauses execution within onTrigger to inspect the event object and the call stack of the mutation.