JAVASCRIPT
Debounce User Input with a Vue 3 Composable
Learn to create a reusable Vue 3 Composition API composable for debouncing user input, perfect for search fields and preventing excessive API calls.
// composables/useDebounce.js
import { ref, watch, onUnmounted } from 'vue';
export function useDebounce(value, delay = 500) {
const debouncedValue = ref(value.value);
let timeoutId;
watch(value, (newValue) => {
clearTimeout(timeoutId);
timeoutId = setTimeout(() => {
debouncedValue.value = newValue;
}, delay);
}, { immediate: true }); // Watch immediately for initial value
onUnmounted(() => {
clearTimeout(timeoutId);
});
return debouncedValue;
}
// App.vue (example usage)
<template>
<input v-model="searchText" placeholder="Search..." />
<p>Debounced search term: {{ debouncedSearchText }}</p>
<!-- Display search results based on debouncedSearchText -->
</template>
<script setup>
import { ref } from 'vue';
import { useDebounce } from './composables/useDebounce';
const searchText = ref('');
const debouncedSearchText = useDebounce(searchText, 300);
// You can now watch debouncedSearchText to trigger API calls
// watch(debouncedSearchText, (newVal) => {
// if (newVal) {
// console.log('Fetching results for:', newVal);
// // Call your API here
// }
// });
</script>
How it works: This snippet demonstrates how to create a `useDebounce` composable in Vue 3. It takes a reactive `ref` and a delay, returning a new reactive `ref` whose value only updates after the input `value` has remained unchanged for the specified `delay` period. This is crucial for optimizing performance in applications by preventing frequent updates or API calls triggered by rapid user input, such as in search bars. The `watch` function monitors the source `value`, resetting a timer on each change. If the timer completes without further changes, the `debouncedValue` is updated. `onUnmounted` ensures the timeout is cleared to prevent memory leaks.