Skip to content

Instantly share code, notes, and snippets.

@Soumyarian98
Created November 6, 2024 04:58
Show Gist options
  • Select an option

  • Save Soumyarian98/485143c4c6d8c9fd35839abad2cdd079 to your computer and use it in GitHub Desktop.

Select an option

Save Soumyarian98/485143c4c6d8c9fd35839abad2cdd079 to your computer and use it in GitHub Desktop.
import { useState, useEffect, useRef } from "react";
function useDebounceValue<T>(value: T, delay: number): T {
const [debouncedValue, setDebouncedValue] = useState<T>(value);
const handlerRef = useRef<number>();
useEffect(() => {
if (handlerRef.current) clearTimeout(handlerRef.current);
handlerRef.current = window.setTimeout(() => {
setDebouncedValue(value);
}, delay);
return () => {
if (handlerRef.current) clearTimeout(handlerRef.current);
};
}, [value, delay]);
return debouncedValue;
}
export default useDebounceValue;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment