UNPKG

beautiful-react-hooks

Version:

A collection of beautiful (and hopefully useful) React hooks to speed-up your components and hooks development

25 lines (24 loc) 983 B
import { useCallback, useEffect, useRef } from 'react'; import throttle from 'lodash.throttle'; import useWillUnmount from './useWillUnmount'; const defaultOptions = { leading: false, trailing: true }; /** * Accepts a function and returns a new throttled yet memoized version of that same function that waits the defined time * before allowing the next execution. * If time is not defined, its default value will be 250ms. */ const useThrottledCallback = (fn, dependencies, wait = 600, options = defaultOptions) => { const throttled = useRef(throttle(fn, wait, options)); useEffect(() => { throttled.current = throttle(fn, wait, options); }, [fn, wait, options]); useWillUnmount(() => { var _a; (_a = throttled.current) === null || _a === void 0 ? void 0 : _a.cancel(); }); return useCallback(throttled.current, dependencies !== null && dependencies !== void 0 ? dependencies : []); }; export default useThrottledCallback;