Last active
February 27, 2019 06:36
-
-
Save brigand/cd1cbd43637c2020cff9cb4abdb0a73e to your computer and use it in GitHub Desktop.
React Hook 'useDebounced' for debouncing event handlers
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
function Foo({ onClick }) { | |
let handler = useDebounced(onClick, { delay: 1000, leading: true }); | |
return <button onClick={handler}>Click me</button>; | |
} |
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
function useDebounced(func, { delay, ...opts}, variables = null) { | |
const ref = useRef(() => { | |
throw new Error(`Can't call debounced function before mount`); | |
}); | |
useEffect(() => { | |
const debounced = lodash.debounce(func, delay, opts); | |
ref.current = debounced; | |
return debounced.cancel; | |
}, variables || [func]); | |
return ref.current; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment