Skip to content

Instantly share code, notes, and snippets.

@JamieDixon
Last active November 26, 2018 10:57
Show Gist options
  • Save JamieDixon/d21a6d66ca9b6fbe4244a9592fc91f10 to your computer and use it in GitHub Desktop.
Save JamieDixon/d21a6d66ca9b6fbe4244a9592fc91f10 to your computer and use it in GitHub Desktop.
const useThrottle = (fn, wait) => {
const throttledRef = useRef(fn);
const lastCallRef = useRef({ fn: () => {}, args: null });
useEffect(
() => {
let isThrottling = false;
throttledRef.current = (...args) => {
if (isThrottling) {
lastCallRef.current = {
fn,
args
};
return;
}
fn(...args);
isThrottling = true;
setTimeout(() => {
isThrottling = false;
const { fn, args } = lastCallRef.current;
fn(...args);
}, wait);
};
},
[wait]
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment