Skip to content

Instantly share code, notes, and snippets.

@gaurangrshah
Created December 14, 2019 21:42
Show Gist options
  • Save gaurangrshah/541ca8db40e9b2a499107a52382eccc3 to your computer and use it in GitHub Desktop.
Save gaurangrshah/541ca8db40e9b2a499107a52382eccc3 to your computer and use it in GitHub Desktop.
react- useDebounce
import { useEffect, useRef, useState } from "react";
const useDebounce = (value, fn, duration) => {
const timeoutRef = useRef(setTimeout(() => undefined));
const [settled, setSettled] = useState(true);
const [numDebounces, setNumDebounces] = useState(-1);
useEffect(() => {
setNumDebounces((num: number) => num + 1);
if (numDebounces <= 0) return; // prevents initially unsettled output on component mount...
clearTimeout(timeoutRef.current);
setSettled(false);
timeoutRef.current = setTimeout(() => {
setSettled(true);
fn();
}, duration);
return () => clearTimeout(timeoutRef.current);
}, [value, duration]);
return settled;
};
export default useDebounce;
import { useRef, useState, useEffect, useCallback } from "react";
let useThrottle = (func, limit) => {
let [args, setArgs] = useState();
let timer = useRef();
let throttledFunction = (...args) => {
setArgs(args || []);
};
let newRunTime = useRef(Date.now());
useEffect(() => {
if (args === undefined) return;
let time = newRunTime.current - Date.now();
if (!timer.current) {
timer.current = setTimeout(() => {
newRunTime.current = Date.now() + limit;
func(...args);
}, time);
return () => {
clearTimeout(timer.current);
timer.current = undefined;
};
}
}, [func, args, limit]);
return useCallback(throttledFunction, []);
};
export { useThrottle };
/*
https://github.com/slynch13/useThrottle/blob/master/example/src/App.js
usage:
const throttleDrag = useThrottle((event, item) => {
event.persist();
console.log("onDrag", event, item);
setDragged(item);
// remove dragged from canvasState ???
}, 200);
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment