Skip to content

Instantly share code, notes, and snippets.

@olayemii
Last active July 16, 2021 16:41
Show Gist options
  • Save olayemii/7fef5c03825b40a4090c00ac2d502a79 to your computer and use it in GitHub Desktop.
Save olayemii/7fef5c03825b40a4090c00ac2d502a79 to your computer and use it in GitHub Desktop.
useDebounce - A hook to debounce a function
import { useEffect, useCallback } from "react";
let debounceTimeout;
const useDebounce = (delay = 1000) => {
const debounceRequest = useCallback(
debounceFunction => {
clearTimeout(debounceTimeout);
debounceTimeout = setTimeout(() => {
debounceFunction();
}, delay);
},
[delay]
);
useEffect(() => {
return () => clearTimeout(debounceTimeout);
}, [debounceRequest]);
return [debounceRequest];
};
export default useDebounce;
@olayemii
Copy link
Author

olayemii commented Apr 2, 2020

To use this hook

  1. Import useDebounce to your component.
  2. Destruct the debouncer `const [debouncer] = useDebounce(1000) // 1000 is the debounce delay
  • Debounce delay is OPTIONAL, defaults to 1000
  1. To debounce any method, send the method as a parameter to your debouncer e.g. debouncer(() =>console.log(1+1)) //the result will be logged after 1000ms

MOTIVATION This was made to delay server calls when making searches, instead of making a request on every keystroke, we debounce to a delayed time after the last keystroke.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment