javascript / intermediate
Snippet
Debounced Reactive References with customRef
The customRef function allows for explicit control over dependency tracking and change triggering. This is ideal for creating debounced inputs where you only want the reactive state to update after a period of inactivity, preventing excessive re-renders or API calls.
snippet.js
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) {let timeout;return customRef((track, trigger) => {return {get() {track();return value;},set(newValue) {clearTimeout(timeout);timeout = setTimeout(() => {value = newValue;trigger();}, delay);}};});}
vue
Breakdown
1
customRef((track, trigger) => {
Initializes a custom ref with tracking and triggering capabilities.
2
track();
Manually marks the dependency as tracked for Vue's reactivity system.
3
trigger();
Manually signals that the value has changed to update subscribers.