javascript / expert
Snippet
Debounced State with Custom Ref
At an expert level, managing performance during frequent updates (like search inputs) requires debouncing at the reactivity level rather than just the event handler. customRef allows you to manually control when dependencies are tracked and when subscribers are triggered, effectively intercepting the update cycle.
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
return customRef((track, trigger) => {
Initializes a custom reactive reference with manual tracking and triggering hooks.
2
track();
Explicitly tells Vue to track this property as a dependency for the current effect.
3
trigger();
Manually notifies all watchers and computed properties that the value has changed after the delay.