Vitron-Front/app/hooks/useDebounce.ts
2026-04-29 01:44:16 +03:30

26 lines
700 B
TypeScript

import { useEffect, useState } from "react";
/**
* A custom hook that debounces a value.
* @param value The value to debounce
* @param delay The delay in milliseconds
* @returns The debounced value
*/
export function useDebounce<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
useEffect(() => {
// Set a timeout to update the debounced value after the specified delay
const handler = setTimeout(() => {
setDebouncedValue(value);
}, delay);
// Cancel the timeout if the value changes before the delay has elapsed
return () => {
clearTimeout(handler);
};
}, [value, delay]);
return debouncedValue;
}