UNPKG

@guoyunhe/use-throttle-callback

Version:
31 lines (30 loc) 718 B
import { useEffect, useRef } from 'react'; export function useThrottleCallback( /** * Callback function */ callback, /** * Timeout in ms * @default 500 */ timeout = 500) { const timeoutRef = useRef(0); const resultRef = useRef(null); const fn = (...args) => { if (timeoutRef.current === 0) { resultRef.current = callback(...args); timeoutRef.current = window.setTimeout(() => { timeoutRef.current = 0; }, timeout); } return resultRef.current; }; useEffect(() => { return () => { window.clearTimeout(timeoutRef.current); timeoutRef.current = 0; }; }, []); return fn; }