PatternHookPerformanceInput
Debounce Hook
A custom React hook for debouncing values. Perfect for search inputs, form validation, and API calls that should wait for user input to settle.
Preview
API calls (last 5):
No searches yet...
Code
import { useState, useEffect } from 'react'
export function useDebounce<T>(value: T, delay: number = 500): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value)
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value)
}, delay)
return () => {
clearTimeout(timer)
}
}, [value, delay])
return debouncedValue
}
// Usage example:
function SearchInput() {
const [query, setQuery] = useState('')
const debouncedQuery = useDebounce(query, 300)
useEffect(() => {
if (debouncedQuery) {
// Perform search API call
console.log('Searching for:', debouncedQuery)
}
}, [debouncedQuery])
return (
<input
type="text"
value={query}
onChange={(e) => setQuery(e.target.value)}
placeholder="Search..."
/>
)
}Looking for more?
Browse the full collection of patterns or check out other exploration topics.