← Back to all snippets
JAVASCRIPT

Debouncing User Input with a Composable

Improve application performance and user experience by creating a reusable Vue 3 composable to debounce user input, preventing excessive function calls on rapid events like typing.

// src/composables/useDebounce.js
import { ref, watch, onUnmounted } from 'vue';

export function useDebounce(value, delay = 500) {
  const debouncedValue = ref(value.value); // Initialize with immediate value
  let timeoutId;

  watch(value, (newValue) => {
    clearTimeout(timeoutId);
    timeoutId = setTimeout(() => {
      debouncedValue.value = newValue;
    }, delay);
  }, { immediate: true }); // immediate: true ensures debouncedValue updates initially

  onUnmounted(() => {
    clearTimeout(timeoutId); // Clear timeout on component unmount
  });

  return debouncedValue;
}

// src/components/DebouncedInput.vue
<template>
  <div>
    <input type="text" v-model="searchTerm" placeholder="Search..." />
    <p>Immediate Search Term: {{ searchTerm }}</p>
    <p>Debounced Search Term: {{ debouncedSearchTerm }}</p>
    <p v-if="debouncedSearchTerm">Searching for: {{ debouncedSearchTerm }}</p>
  </div>
</template>

<script setup>
import { ref, watch } from 'vue';
import { useDebounce } from '../composables/useDebounce';

const searchTerm = ref('');
const debouncedSearchTerm = useDebounce(searchTerm, 700);

watch(debouncedSearchTerm, (newVal) => {
  if (newVal) {
    // Perform API call or heavy operation here
    console.log('Performing search for:', newVal);
  }
});
</script>
How it works: Debouncing is a technique to delay the execution of a function until after a certain amount of time has passed without further activity. This reusable Vue 3 composable, `useDebounce`, takes a reactive value and a delay. It returns a new reactive value that only updates after the input value has stopped changing for the specified delay. This is crucial for optimizing operations like API calls on user input, preventing them from firing too frequently.

Need help integrating this into your project?

Our team of expert developers can help you build your custom application from scratch.

Hire DigitalCodeLabs