Skip to content

Instantly share code, notes, and snippets.

@GGrassiant
Last active September 30, 2020 21:58
Show Gist options
  • Select an option

  • Save GGrassiant/a2cc5300748943d0fae3726ca37d8a66 to your computer and use it in GitHub Desktop.

Select an option

Save GGrassiant/a2cc5300748943d0fae3726ca37d8a66 to your computer and use it in GitHub Desktop.
React Throttle
import { useEffect, useRef, useState } from 'react';
import useUnmount from './useUnmount';
const useThrottleFn = <T, U extends any[]>(fn: (...args: U) => T, ms: number = 200, args: U) => {
const [state, setState] = useState<T | null>(null);
const timeout = useRef<ReturnType<typeof setTimeout>>();
const nextArgs = useRef<U>();
useEffect(() => {
if (!timeout.current) {
setState(fn(...args));
const timeoutCallback = () => {
if (nextArgs.current) {
setState(fn(...nextArgs.current));
nextArgs.current = undefined;
timeout.current = setTimeout(timeoutCallback, ms);
} else {
timeout.current = undefined;
}
};
timeout.current = setTimeout(timeoutCallback, ms);
} else {
nextArgs.current = args;
}
return () => timeout.current && clearTimeout(timeout.current);
}, args);
return state;
};
export default useThrottleFn;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment