0 day streak
javascript / expert
Snippet

Custom Debounced Ref Factory

Custom ref factories allow fine-grained control over reactivity. This implementation debounces state updates to prevent excessive re-renders during rapid input by manually controlling track() and trigger() calls.

snippet.js
javascript
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
import { customRef } from 'vue';
export function useDebouncedRef(value, delay = 200) {
return customRef((track, trigger) => {
let timeout;
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
}
};
});
}
vue
Breakdown
1
return customRef((track, trigger) => {
Initialize a custom reactive reference with manual dependency tracking and trigger controls.
2
get() { track(); return value; },
Registers the current effect as a dependency of this ref using the track() function.
3
set(newValue) { ... trigger(); }
Manually notifies Vue to re-run dependent effects only after the specified timeout.