Skip to content

Instantly share code, notes, and snippets.

@SebastianHGonzalez
Created August 29, 2019 12:47
Show Gist options
  • Select an option

  • Save SebastianHGonzalez/7ce4b907800f6a4622c6c8c165eb7435 to your computer and use it in GitHub Desktop.

Select an option

Save SebastianHGonzalez/7ce4b907800f6a4622c6c8c165eb7435 to your computer and use it in GitHub Desktop.
import { useEffect } from "react";
/**
* Just like useEffect but it delays execution and debounces by the given delay
*
* @param {import("react").EffectCallback} effect
* @param {Number} delay
* @param {import("react").DependencyList} deps
*/
export default function useDebounce(effect, delay, deps) {
return useEffect(() => {
let destructor = noop;
const timeout = setTimeout(() => {
destructor = effect() || noop;
}, delay);
return () => {
clearTimeout(timeout);
destructor();
};
}, [effect, delay, ...deps]);
}
function noop() {}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment