useThrottleFn
React hooks that throttle function
useThrottleFn 建立一個節流版本的函式,確保在指定的時間間隔內最多只執行一次。與防抖不同,節流會在間隔開始時執行函式,並在時間視窗內忽略後續呼叫。
使用場景
- 在捲動或調整大小事件處理中限制回呼的執行頻率
- 限制 API 請求的發送頻率(例如搜尋建議)
- 以固定的最大頻率更新 UI 元素
注意事項
- 前緣和後緣:可設定是否在間隔的前緣(立即執行)和/或後緣(延遲執行)觸發。
- 取消:回傳的物件包含
cancel方法以取消待處理的呼叫。 - 相關 hooks:另請參閱
useThrottle用於值的節流,以及useDebounceFn用於防抖函式。
Usage
Live Editor
function Demo() { const [value, setValue] = useState(0); const { run } = useThrottleFn(() => { setValue(value + 1); }, 500); return ( <div> <p style={{ marginTop: 16 }}> 點擊次數:{value} </p> <button type="button" onClick={run}> 快速點擊! </button> </div> ); };
Result
API
useThrottleFn
Returns
{ run: _.DebouncedFunc<(...args_0: Parameters<T>) => ReturnType<T>>; cancel: () => void; flush: any; }: 具有以下元素的對象:
- run:執行函數。
- cancel:取消執行函數。
- flush: 立即執行函數
Arguments
| 參數名 | 描述 | 類型 | 預設值 |
|---|---|---|---|
| fn | 要节流的函数 | T (必填) | - |
| wait | 间隔时间 | number | undefined | - |
| options | 传递给 lodash.throttle 的属性 | _.ThrottleSettings | undefined | - |