JAVASCRIPT
Create a Custom Composable for Debounced Input
Implement a reusable Vue 3 custom composable (`useDebounce`) to efficiently handle debounced input, preventing excessive function calls.
// composables/useDebounce.js
import { ref, customRef } from 'vue';
export function useDebounce(value, delay = 500) {
let timeout;
return customRef((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
},
};
});
}
/*
// How to use in a Vue Component (e.g., SearchInput.vue)
<script setup>
import { ref, watch } from 'vue';
import { useDebounce } from './composables/useDebounce';
const searchTerm = ref('');
const debouncedSearchTerm = useDebounce(searchTerm, 500);
watch(debouncedSearchTerm, (newValue) => {
if (newValue) {
console.log('Performing search for:', newValue);
// Here you would typically dispatch an API request
} else {
console.log('Search term cleared.');
}
});
</script>
<template>
<div>
<input type="text" v-model="searchTerm" placeholder="Type to search...">
<p>Current input: {{ searchTerm }}</p>
<p>Debounced input: {{ debouncedSearchTerm }}</p>
</div>
</template>
*/
How it works: This snippet introduces a `useDebounce` custom composable, leveraging `customRef` to create a reactive reference that only updates its value after a specified delay. This is highly useful for input fields (like search bars) to prevent frequent API calls as the user types, improving performance and reducing server load. The `watch` function then reacts to the debounced value, executing logic only after the user pauses typing.