Skip to content

Instantly share code, notes, and snippets.

@maurocen
Created July 5, 2020 20:40
Show Gist options
  • Save maurocen/efeb535ac332372cbf6ff8e904c84a97 to your computer and use it in GitHub Desktop.
Save maurocen/efeb535ac332372cbf6ff8e904c84a97 to your computer and use it in GitHub Desktop.
A hook to debounce events
import { useState } from 'react';
const useDebounce = () => {
const [timer, setTimer] = useState(null);
const debounce = (callback, time) => (e) => {
e.persist();
if (timer) {
clearTimeout(timer);
}
const timeout = setTimeout(() => {
callback(e);
setTimer(null);
}, time);
setTimer(timeout);
}
return debounce;
};
export default useDebounce;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment