Skip to content

Instantly share code, notes, and snippets.

@brigand
Last active February 27, 2019 06:36
Show Gist options
  • Save brigand/cd1cbd43637c2020cff9cb4abdb0a73e to your computer and use it in GitHub Desktop.
Save brigand/cd1cbd43637c2020cff9cb4abdb0a73e to your computer and use it in GitHub Desktop.
React Hook 'useDebounced' for debouncing event handlers
function Foo({ onClick }) {
let handler = useDebounced(onClick, { delay: 1000, leading: true });
return <button onClick={handler}>Click me</button>;
}
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