JAVASCRIPT
Optimizing Input Performance with a Debounced Vue 3 Composable
Implement a custom Vue 3 composable to debounce user input, reducing unnecessary function calls and API requests, thereby improving application performance and responsiveness.
// composables/useDebouncedRef.js
import { customRef } from 'vue';
export function useDebouncedRef(value, delay = 500) {
let timeout;
return customRef((track, trigger) => {
return {
get() {
track();
return value;
},
set(newValue) {
clearTimeout(timeout);
timeout = setTimeout(() => {
value = newValue;
trigger();
}, delay);
},
};
});
}
// MyComponent.vue
<template>
<div>
<label for="search-input">Search:</label>
<input type="text" id="search-input" v-model="searchTerm" placeholder="Type to search..." />
<p>Debounced search term: {{ searchTerm }}</p>
<p v-if="searchTerm">Simulating API call for: <strong>{{ searchTerm }}</strong></p>
</div>
</template>
<script setup>
import { useDebouncedRef } from './composables/useDebouncedRef';
// Creates a debounced ref with a 500ms delay
const searchTerm = useDebouncedRef('', 500);
// You could also watch searchTerm if you need to perform side effects
// watch(searchTerm, (newValue) => {
// if (newValue) {
// console.log('Performing API search for:', newValue);
// }
// }, { immediate: true });
</script>
<style scoped>
input {
padding: 8px;
margin-right: 10px;
border: 1px solid #ddd;
border-radius: 4px;
}
</style>
How it works: This snippet introduces `useDebouncedRef`, a Vue 3 composable utilizing `customRef` to create a debounced reactive reference. When the value of `searchTerm` (or any ref created with `useDebouncedRef`) is set, it delays updating the actual `value` and triggering reactivity until a specified `delay` has passed without further changes. This is extremely useful for optimizing performance on inputs that trigger expensive operations like API calls or complex filtering, preventing rapid, unnecessary executions as the user types.