(cb: () => void, delay: number)
| 2 | import { useCallback, useEffect, useRef } from 'react'; |
| 3 | |
| 4 | export function useThrottle(cb: () => void, delay: number) { |
| 5 | const options = { leading: true, trailing: false }; // add custom lodash options |
| 6 | const cbRef = useRef(cb); |
| 7 | // use mutable ref to make useCallback/throttle not depend on `cb` dep |
| 8 | useEffect(() => { |
| 9 | cbRef.current = cb; |
| 10 | }); |
| 11 | return useCallback( |
| 12 | throttle(() => cbRef.current(), delay, options), |
| 13 | [delay], |
| 14 | ); |
| 15 | } |