Created
March 19, 2019 16:10
-
-
Save danakt/ab653afa44039908e69d64ea7eac458f to your computer and use it in GitHub Desktop.
React hook for creating debounced callback
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
export const useDebouncedCallback = <T extends (...args: any) => void>( | |
callback: T, | |
time: number, | |
deps: React.DependencyList | |
) => { | |
const timerRef = React.useRef<number>(-1); | |
const memoizedCallback = React.useCallback<T>( | |
((...args: any): void => { | |
clearTimeout(timerRef.current); | |
timerRef.current = setTimeout(() => callback(...args), time); | |
}) as T, | |
deps | |
); | |
return memoizedCallback; | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment