function useAsyncThrottler<TFn, TSelected>(
fn,
options,
selector): ReactAsyncThrottler<TFn, TSelected>
function useAsyncThrottler<TFn, TSelected>(
fn,
options,
selector): ReactAsyncThrottler<TFn, TSelected>
Definiert in: react-pacer/src/async-throttler/useAsyncThrottler.ts:160
Ein Low-Level-React-Hook, der eine AsyncThrottler-Instanz erstellt, um die Häufigkeit zu begrenzen, mit der eine asynchrone Funktion ausgeführt werden kann.
Dieser Hook ist flexibel und zustandsverwaltungsagnostisch konzipiert – er gibt einfach eine Throttler-Instanz zurück, die Sie mit jeder Zustandsverwaltungslösung (useState, Redux, Zustand, Jotai usw.) integrieren können.
Asynchrones Throttling stellt sicher, dass eine asynchrone Funktion unabhängig davon, wie oft sie aufgerufen wird, höchstens einmal innerhalb eines bestimmten Zeitfensters ausgeführt wird. Dies ist nützlich für die Ratenbegrenzung teurer API-Aufrufe, Datenbankoperationen oder anderer asynchroner Aufgaben.
Im Gegensatz zum nicht-asynchronen Throttler unterstützt diese asynchrone Version die Rückgabe von Werten aus der gedrosselten Funktion, was sie ideal für API-Aufrufe und andere asynchrone Operationen macht, bei denen Sie das Ergebnis des maybeExecute-Aufrufs anstelle des Setzens des Ergebnisses auf einer Zustandsvariable innerhalb der gedrosselten Funktion wünschen.
Fehlerbehandlung
Der Hook verwendet TanStack Store für reaktives Zustandsmanagement. Der Parameter selector ermöglicht es Ihnen anzugeben, welche Zustandsänderungen ein erneutes Rendern auslösen, wodurch die Leistung optimiert wird, indem unnötige erneute Renderings verhindert werden, wenn irrelevante Zustandsänderungen auftreten.
Standardmäßig erfolgen keine reaktiven Zustands-Subscriptions und Sie müssen das Zustands-Tracking durch Bereitstellen einer Selector-Funktion aktivieren. Dies verhindert unnötige Renderings und gibt Ihnen die volle Kontrolle darüber, wann Ihre Komponente aktualisiert wird. Nur wenn Sie einen Selector bereitstellen, wird die Komponente neu gerendert, wenn sich die ausgewählten Zustandswerte ändern.
Verfügbare Zustandseigenschaften
• TFn extends AnyAsyncFunction
• TSelected = {}
TFn
AsyncThrottlerOptions<TFn>
(state) => TSelected
ReactAsyncThrottler<TFn, TSelected>
// Default behavior - no reactive state subscriptions
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data; // Return value is preserved
},
{ wait: 1000 }
);
// Opt-in to re-render when execution state changes (optimized for loading indicators)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
isExecuting: state.isExecuting,
isPending: state.isPending,
status: state.status
})
);
// Opt-in to re-render when results are available (optimized for data display)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
lastResult: state.lastResult,
successCount: state.successCount,
settleCount: state.settleCount
})
);
// Opt-in to re-render when error state changes (optimized for error handling)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{
wait: 1000,
onError: (error) => console.error('API call failed:', error)
},
(state) => ({
errorCount: state.errorCount,
status: state.status
})
);
// Opt-in to re-render when timing information changes (optimized for timing displays)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
lastExecutionTime: state.lastExecutionTime,
nextExecutionTime: state.nextExecutionTime
})
);
// With state management and return value
const [data, setData] = useState(null);
const { maybeExecute, state } = useAsyncThrottler(
async (query) => {
const result = await searchAPI(query);
setData(result);
return result; // Return value can be used by the caller
},
{
wait: 2000,
leading: true, // Execute immediately on first call
trailing: false // Skip trailing edge updates
}
);
// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult } = state;
// Default behavior - no reactive state subscriptions
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data; // Return value is preserved
},
{ wait: 1000 }
);
// Opt-in to re-render when execution state changes (optimized for loading indicators)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
isExecuting: state.isExecuting,
isPending: state.isPending,
status: state.status
})
);
// Opt-in to re-render when results are available (optimized for data display)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
lastResult: state.lastResult,
successCount: state.successCount,
settleCount: state.settleCount
})
);
// Opt-in to re-render when error state changes (optimized for error handling)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{
wait: 1000,
onError: (error) => console.error('API call failed:', error)
},
(state) => ({
errorCount: state.errorCount,
status: state.status
})
);
// Opt-in to re-render when timing information changes (optimized for timing displays)
const asyncThrottler = useAsyncThrottler(
async (id: string) => {
const data = await api.fetchData(id);
return data;
},
{ wait: 1000 },
(state) => ({
lastExecutionTime: state.lastExecutionTime,
nextExecutionTime: state.nextExecutionTime
})
);
// With state management and return value
const [data, setData] = useState(null);
const { maybeExecute, state } = useAsyncThrottler(
async (query) => {
const result = await searchAPI(query);
setData(result);
return result; // Return value can be used by the caller
},
{
wait: 2000,
leading: true, // Execute immediately on first call
trailing: false // Skip trailing edge updates
}
);
// Access the selected state (will be empty object {} unless selector provided)
const { isExecuting, lastResult } = state;
Ihre wöchentliche Dosis JavaScript-Nachrichten. Jeden Montag kostenlos an über 100.000 Entwickler geliefert.