You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

61 lines
1.2 KiB

/**
* Hook
* 使 lodash-es throttle
*/
import { useEffect, useMemo, useRef } from 'react';
import { throttle } from 'lodash-es';
/**
* Hook
* @param callback
* @param delay
* @param options
* @returns
*/
export function useThrottle<T extends (...args: any[]) => any>(
callback: T,
delay: number = 300,
options?: {
leading?: boolean;
trailing?: boolean;
}
): T {
const callbackRef = useRef(callback);
// 更新 callback ref
useEffect(() => {
callbackRef.current = callback;
}, [callback]);
// 创建节流函数
const throttledCallback = useMemo(() => {
const func = (...args: Parameters<T>) => {
callbackRef.current(...args);
};
return throttle(func, delay, options);
}, [delay, options]);
// 清理
useEffect(() => {
return () => {
throttledCallback.cancel();
};
}, [throttledCallback]);
return throttledCallback as T;
}
/**
* 使
1 month ago
*
* const handleScroll = useThrottle((event) => {
* console.log('Scrolling:', event);
* }, 200);
1 month ago
*
* <ScrollView onScroll={handleScroll}>
* ...
* </ScrollView>
*/