Vue 3 useDebounce Composable

Vue 3 useDebounce Composable

Vue 3 useDebounce Composable

Prevent excessive API calls by debouncing user input with this simple composable.

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

export function useDebounce(value, delay = 300) {
  const debounced = ref(value.value)

  watch(value, (newVal) => {
    const timer = setTimeout(() => {
      debounced.value = newVal
    }, delay)
    return () => clearTimeout(timer)
  })

  return debounced
}
<!-- Usage in a component -->
<script setup>
import { ref, watch } from 'vue'
import { useDebounce } from '@/composables/useDebounce'

const search   = ref('')
const debounced = useDebounce(search, 400)

watch(debounced, (val) => {
  if (val) fetchResults(val)
})
</script>

<template>
  <input v-model="search" placeholder="Search..." />
</template>
All Comments