function useAsyncDebouncer<TFn, TSelected>(
fn,
options,
selector): ReactAsyncDebouncer<TFn, TSelected>
function useAsyncDebouncer<TFn, TSelected>(
fn,
options,
selector): ReactAsyncDebouncer<TFn, TSelected>
定义于: react-pacer/src/async-debouncer/useAsyncDebouncer.ts:149
一个低级别的 React hook,用于创建一个 AsyncDebouncer 实例来延迟异步函数的执行。
这个 hook 被设计成灵活且与状态管理无关的——它只返回一个 debouncer 实例,您可以将其集成到任何状态管理解决方案中(useState、Redux、Zustand、Jotai 等)。
异步防抖确保异步函数仅在自上次调用以来指定的延迟时间过后才执行。每次新的调用都会重置延迟计时器。这对于处理窗口大小调整或输入更改等频繁事件非常有用,因为您只想在事件停止发生后执行处理程序。
与节流(节流允许在固定间隔内执行)不同,防抖会阻止任何执行,直到函数在指定的延迟时间内停止被调用。
与非异步 Debouncer 不同,这个异步版本支持从防抖函数返回值为,这使得它非常适合 API 调用和其他异步操作,您希望在 maybeExecute 调用时获得结果,而不是在防抖函数内部将结果设置为状态变量。
错误处理
该 hook 使用 TanStack Store 进行响应式状态管理。selector 参数允许您指定哪些状态更改将触发重新渲染,通过防止不相关的状态更改引起不必要的重新渲染来优化性能。
默认情况下,将不会进行响应式状态订阅,并且您必须通过提供选择器函数来选择加入状态跟踪。这可以防止不必要的重新渲染,并让您完全控制组件何时更新。只有当您提供选择器时,组件才会根据所选状态值的变化而重新渲染。
可用的状态属性
• TFn extends AnyAsyncFunction
• TSelected = {}
TFn
AsyncDebouncerOptions<TFn>
(state) => TSelected
ReactAsyncDebouncer<TFn, TSelected>
// Default behavior - no reactive state subscriptions
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 }
);
// Opt-in to re-render when execution state changes (optimized for loading indicators)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 },
(state) => ({
isExecuting: state.isExecuting,
isPending: state.isPending
})
);
// Opt-in to re-render when results are available (optimized for data display)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 },
(state) => ({
lastResult: state.lastResult,
successCount: state.successCount
})
);
// Opt-in to re-render when error state changes (optimized for error handling)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{
wait: 500,
onError: (error) => console.error('Search failed:', error)
},
(state) => ({
errorCount: state.errorCount,
status: state.status
})
);
// With state management
const [results, setResults] = useState([]);
const { maybeExecute, state } = useAsyncDebouncer(
async (searchTerm) => {
const data = await searchAPI(searchTerm);
setResults(data);
},
{
wait: 300,
leading: true, // Execute immediately on first call
trailing: false, // Skip trailing edge updates
onError: (error) => {
console.error('API call failed:', error);
}
}
);
// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult } = state;
// Default behavior - no reactive state subscriptions
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 }
);
// Opt-in to re-render when execution state changes (optimized for loading indicators)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 },
(state) => ({
isExecuting: state.isExecuting,
isPending: state.isPending
})
);
// Opt-in to re-render when results are available (optimized for data display)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{ wait: 500 },
(state) => ({
lastResult: state.lastResult,
successCount: state.successCount
})
);
// Opt-in to re-render when error state changes (optimized for error handling)
const searchDebouncer = useAsyncDebouncer(
async (query: string) => {
const results = await api.search(query);
return results;
},
{
wait: 500,
onError: (error) => console.error('Search failed:', error)
},
(state) => ({
errorCount: state.errorCount,
status: state.status
})
);
// With state management
const [results, setResults] = useState([]);
const { maybeExecute, state } = useAsyncDebouncer(
async (searchTerm) => {
const data = await searchAPI(searchTerm);
setResults(data);
},
{
wait: 300,
leading: true, // Execute immediately on first call
trailing: false, // Skip trailing edge updates
onError: (error) => {
console.error('API call failed:', error);
}
}
);
// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult } = state;
您的每周 JavaScript 资讯。每周一免费发送给超过 10 万开发者。