import throttle from 'lodash.throttle' ; import { useRef , useEffect } from 'react' ; import useCreation from './useCreation' ; import { Options } from './options' ; type Fn = ( ... args : any ) => any ; function useThrottleFn < T extends Fn > ( fn , options ? ) { const fnRef = useRef < T > ( fn ) ; fnRef . current = fn ; const wait = options ?. wait ?? 1000 ; const throttled = useCreation ( ( ) => throttle < T > ( ( ( ... args ) => { return fnRef . current ( ... args ) ; } ) as T , wait , options ) , [ ] ) ; useEffect ( ( ) => { throttled . cancel ( ) ; } , [ ] ) ; return { run : throttled as unknown as T , cancel : throttled . cancel , flush : throttled . flush , } ; } export default useThrottleFn ;