JAVASCRIPT

Creating a Reusable Debounce Input Composable in Vue 3

Enhance user experience by implementing a custom Vue 3 composable for debouncing input fields, reducing unnecessary function calls and improving performance for search or validation.

// composables/useDebouncedRef.js
import { ref, customRef } from 'vue';

export function useDebouncedRef(value, delay = 200) {
  let timeout;
  return customRef((track, trigger) => {
    return {
      get() {
        track();
        return value;
      },
      set(newValue) {
        clearTimeout(timeout);
        timeout = setTimeout(() => {
          value = newValue;
          trigger();
        }, delay);
      }
    };
  });
}

// App.vue (or any component)
<template>
  <div>
    <input type="text" v-model="searchTerm" placeholder="Type to search (debounced)..." />
    <p>Current (debounced) search term: {{ searchTerm }}</p>
  </div>
</template>

<script setup>
import { useDebouncedRef } from './composables/useDebouncedRef';

const searchTerm = useDebouncedRef('', 500); // Debounce for 500ms
</script>
How it works: This snippet shows how to create a custom Vue 3 composable, `useDebouncedRef`, which uses Vue's `customRef` to implement a debounced reactive reference. When `searchTerm` is updated (e.g., from an input field), its value is only propagated after a specified `delay` (here, 500ms) without further updates. This is highly useful for optimizing performance in scenarios like search inputs or real-time validation, preventing excessive function calls by waiting for the user to pause typing.

Need help integrating this into your project?

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

Hire DigitalCodeLabs