Created
November 6, 2024 04:58
-
-
Save Soumyarian98/485143c4c6d8c9fd35839abad2cdd079 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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