Created
December 11, 2019 12:22
-
-
Save julioxavierr/965fd5551cdb981a8305d006740ac034 to your computer and use it in GitHub Desktop.
useDebounce hook with TS + underscorejs
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'; | |
import _ from 'underscore'; | |
const DEFAULT_DEBOUNCE_TIMEOUT = 1000; | |
/** | |
* Debounce fast changing value. | |
* The debounced value will only reflect the latest value when the hook has not been called for the specified time period. | |
*/ | |
function useDebounce( | |
value: any, | |
wait: number = DEFAULT_DEBOUNCE_TIMEOUT, | |
immediate?: boolean, | |
) { | |
const [debouncedValue, setDebouncedValue] = useState(value); | |
useEffect(() => { | |
const debouncedFn = _.debounce( | |
() => setDebouncedValue(value), | |
wait, | |
immediate, | |
); | |
debouncedFn(); | |
// Cancel the timeout if value changes | |
// Timeout gets cleared and restarted | |
return () => { | |
debouncedFn.cancel(); | |
}; | |
}, [immediate, value, wait]); // Only re-call effect if value or delay changes | |
return debouncedValue; | |
} | |
export default useDebounce; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment