UNPKG

use-lodash-debounce-throttle

Version:

Bring debounce & throttle of lodash version to react-hooks

36 lines (31 loc) 967 B
import { useEffect, useRef } from 'react'; import useStableMemo from './use-stable-memo'; function createCancelableHook(createFn, depFn) { return function (fn, wait, options, deps) { var compareParams = depFn(wait, options).concat(deps || []); var debouncedFn = useRef(undefined); var fnRef = useRef(fn); fnRef.current = fn; function createDebounce() { return createFn(function () { return fnRef.current && fnRef.current.apply(fnRef, arguments); }, wait, options); } useStableMemo(function () { if (debouncedFn.current) { // only call when update debouncedFn.current.cancel(); } debouncedFn.current = createDebounce(); }, compareParams); useEffect(function () { return function () { if (debouncedFn.current) { debouncedFn.current.cancel(); } }; }, []); return debouncedFn.current; }; } export default createCancelableHook;