A simple React hook to debounce a value with configurable delay. Useful for search inputs and expensive updates.
import { useState, useEffect } from 'react';
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
const timer = setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => clearTimeout(timer);
}, [value, delay]);
return debouncedValue;
}Paste it into your project (e.g. a hooks folder or next to the component that uses it).
Call useDebounce(stateValue, 300) to get a value that updates only after 300ms of no changes. Typical use: debounce search input before calling an API.
const debouncedQuery = useDebounce(searchInput, 300);