Created
February 28, 2021 14:03
-
-
Save apherio/7034d3279384e4779cd57c17848a0d5c to your computer and use it in GitHub Desktop.
debouncing functionality.
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 } 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