Created
March 9, 2020 01:19
-
-
Save jmcmullen/9561e0bcd2f7998ec7f556b2627f7e88 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 { useState, useEffect } from 'react'; | |
function useDebounce<T>( | |
initialValue: T, | |
time: number | |
): [T, T, React.Dispatch<T>] { | |
const [value, setValue] = useState<T>(initialValue); | |
const [debouncedValue, setDebouncedValue] = useState<T>(initialValue); | |
useEffect(() => { | |
const debounce = setTimeout(() => { | |
setDebouncedValue(value); | |
}, time); | |
return () => { | |
clearTimeout(debounce); | |
}; | |
}, [value, time]); | |
return [debouncedValue, value, setValue]; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment