Skip to content

Instantly share code, notes, and snippets.

@0xLDev
Created December 18, 2021 08:37
Show Gist options
  • Save 0xLDev/f6017722c4fc16e1e364138b0b04016a to your computer and use it in GitHub Desktop.
Save 0xLDev/f6017722c4fc16e1e364138b0b04016a to your computer and use it in GitHub Desktop.
import { useEffect, useState, useRef } from 'react';
export const useThrottle = (value, delay) => {
const [throttledValue, setThrottledValue] = useState(value);
const valueRef = useRef(value);
useEffect(() => {
valueRef.current = value;
}, [value]);
useEffect(() => {
const intervalHandle = setInterval(() => {
setThrottledValue(valueRef.current);
}, delay);
return () => {
clearInterval(intervalHandle);
};
}, [delay]);
return throttledValue;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment