Created
October 6, 2022 07:40
-
-
Save OlivierJM/13358a5a68e38d0d69c9eabd79a67b71 to your computer and use it in GitHub Desktop.
This file contains 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 { useEffect, useState } from 'react'; | |
/** | |
* Debounce a value to avoid constant calls to the server | |
* @param value it can be a string or a number | |
* @param delay the amount in milliseconds that will be delayed | |
* @returns The give value debounced | |
*/ | |
export default function useDebounceValue<T>(value: T, delay: number): T { | |
const [debouncedValue, setDebouncedValue] = useState<T>(value); | |
useEffect(() => { | |
const delayHandler = setTimeout(() => { | |
setDebouncedValue(value); | |
}, delay); | |
return () => { | |
clearTimeout(delayHandler); | |
}; | |
}, [value, delay]); | |
return debouncedValue; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment