Files
rn-app/hooks/useThrottle.ts

61 lines
1.2 KiB
TypeScript
Raw Normal View History

2025-11-04 13:27:19 +08:00
/**
* 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;
}
/**
* 使
2025-11-05 17:24:55 +08:00
*
2025-11-04 13:27:19 +08:00
* const handleScroll = useThrottle((event) => {
* console.log('Scrolling:', event);
* }, 200);
2025-11-05 17:24:55 +08:00
*
2025-11-04 13:27:19 +08:00
* <ScrollView onScroll={handleScroll}>
* ...
* </ScrollView>
*/