VUE

useDebounce Composable

A composable for debouncing function calls with configurable delay

Vue3ComposablesDebouncePerformance

Code

import { ref, watch, type Ref } from 'vue';

interface UseDebounceOptions {
  delay: number;
  immediate?: boolean;
}

export function useDebounce<T>(value: Ref<T>, options: UseDebounceOptions = { delay: 300, immediate: false }): Ref<T> {
  const debouncedValue = ref<T>(value.value) as Ref<T>;
  let timeoutId: ReturnType<typeof setTimeout> | null = null;

  watch(value, (newVal) => {
    __TOKEN_16__ (options.immediate && timeoutId === null) {
      debouncedValue.value = newVal;
      return;
    }

    __TOKEN_18__ (timeoutId) clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      debouncedValue.value = newVal;
    }, options.delay);
  }, { immediate: options.immediate });

  // Cleanup timeout on unmount
  const cleanup = () => {
    __TOKEN_20__ (timeoutId) clearTimeout(timeoutId);
  };

  // Return debounced value and cleanup (optional)
  return debouncedValue;
}

// Usage example
// const searchQuery = ref('');
// const debouncedSearch = useDebounce(searchQuery, { delay: 500 });
// watch(debouncedSearch, (val) => { /* fetch search results */ });