0 day streak
javascript / expert
Snippet

Custom Reactive Logic with customRef

customRef provides explicit control over dependency tracking and trigger notifications. This is powerful for implementing debouncing, throttling, or integrating with non-standard data sources where you want to determine exactly when a re-render should happen.

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';
function useDebouncedRef(value, delay = 200) {
let timeout;
return customRef((track, trigger) => ({
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
}
}));
}
vue
Breakdown
1
customRef((track, trigger) => ({ ... }));
Factory function providing lower-level reactivity hooks.
2
track();
Tells Vue that the current effect depends on this ref's value.
3
trigger();
Tells Vue to re-run all effects that depend on this ref.