QA
Intermediate LevelVue JS

How do you build a debounced input ref using customRef() in Vue 3?

❓ Interview Prompt: Explain customRef(), tracking getter dependencies (track), triggering setter updates (trigger), and debounced search inputs.

'customRef()' allows customizing a ref's getter and setter behavior with explicit dependency tracking ('track()') and update triggering ('trigger()').

Building a Debounced Search Ref:

By wrapping setter logic in a 'setTimeout', setting a new value clears the previous timer and delays firing 'trigger()', creating an elegant debounced ref for search inputs!

Code Implementation Example

javascript
import { customRef } from 'vue';

export function useDebouncedRef(value, delay = 300) {
  let timeout;
  return customRef((track, trigger) => ({
    get() {
      track(); // Tell Vue to track dependency
      return value;
    },
    set(newValue) {
      clearTimeout(timeout);
      timeout = setTimeout(() => {
        value = newValue;
        trigger(); // Tell Vue to trigger UI update after delay!
      }, delay);
    }
  }));
}
💡Creating a custom debounced ref using customRef track and trigger callbacks.
🎯 Interview Key Takeaway

Use customRef() with track() and trigger() to build custom reactive primitives like debounced input refs.

#customRef#Debounce#Reactivity#Intermediate
Back to all Vue JS Questions→

More Vue JS Interview Questions

Beginner LevelVue JS

What is the difference between Options API and Composition API in Vue 3?

Beginner LevelVue JS

What is the difference between ref() and reactive() in Vue 3?

Beginner LevelVue JS

What is the difference between computed properties, methods, and watch/watchEffect?