javascript / expert
Snippet
Scheduling Debounced State Updates via CustomRef Explicit Triggers
customRef provides explicit control over dependency tracking (track) and subscriber notification (trigger). By delaying the call to trigger inside a timeout, reactivity updates are debounced cleanly at the ref boundary.
snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import { customRef } from 'vue';export function useDebouncedRef(initialValue, delayMs = 300) {let timeoutId;return customRef((track, trigger) => ({get() {track();return initialValue;},set(newValue) {clearTimeout(timeoutId);timeoutId = setTimeout(() => {initialValue = newValue;trigger();}, delayMs);}}));}
vue
Breakdown
1
return customRef((track, trigger) => ({
Constructs a customized reactive reference with explicit track and trigger hooks.
2
trigger();
Notifies reactive subscribers only after the asynchronous timer completes, suppressing intermediate re-renders.