함수: useAsyncThrottler()
function useAsyncThrottler<TFn, TSelected>(
fn,
options,
selector): ReactAsyncThrottler<TFn, TSelected>;
정의 위치: react-pacer/src/async-throttler/useAsyncThrottler.ts:225
비동기 함수의 실행 빈도를 제한하는 AsyncThrottler 인스턴스를 생성하는 하위 수준 React 훅입니다.
유연하고 상태 관리 방식에 구애받지 않도록 설계되었습니다. 스로틀러 인스턴스만 반환하므로 어떤 상태 관리 솔루션(useState, Redux, Zustand, Jotai 등)과도 통합할 수 있습니다.
비동기 스로틀은 호출 횟수와 관계없이 지정된 시간 윈도우 안에서 비동기 함수가 최대 한 번만 실행되도록 합니다. 비용이 큰 API 호출, 데이터베이스 작업 또는 기타 비동기 작업의 요청률을 제한할 때 유용합니다.
비동기가 아닌 Throttler와 달리 이 비동기 버전은 스로틀된 함수의 값을 반환할 수 있습니다.
따라서 스로틀된 함수 안에서 결과를 상태 변수에 설정하는 대신 maybeExecute 호출 결과를 사용하려는
API 호출 및 기타 비동기 작업에 적합합니다.
오류 처리:
onError핸들러를 제공하면 오류 및 스로틀러 인스턴스와 함께 호출됩니다.throwOnError가 true이면(onError 핸들러가 없을 때의 기본값) 오류가 발생합니다.throwOnError가 false이면(onError 핸들러가 있을 때의 기본값) 오류가 처리된 것으로 간주됩니다.- onError와 throwOnError를 함께 사용할 수 있으며, 오류가 발생하기 전에 핸들러가 호출됩니다.
- 내부 AsyncThrottler 인스턴스를 사용해 오류 상태를 확인할 수 있습니다.
상태 관리와 셀렉터
훅은 반응형 상태 관리에 TanStack Store를 사용합니다. 다음 두 가지 방식으로 상태 변경을 구독할 수 있습니다.
1. throttler.Subscribe HOC 사용(컴포넌트 트리 구독에 권장)
Subscribe HOC를 사용하면 컴포넌트 트리 깊은 곳의 상태 변경을 구독할 때
훅에 셀렉터를 전달할 필요가 없습니다. 자식 컴포넌트에서 상태를
구독하려는 경우에 적합합니다.
2. selector 매개변수 사용(훅 수준 구독)
selector 매개변수를 사용하면 어떤 상태 변경이 재렌더링을 트리거할지 지정할 수 있으며
관련 없는 상태가 변경될 때 불필요한 재렌더링을 방지하여 훅 수준의 성능을 최적화합니다.
기본적으로 반응형 상태 구독은 없습니다. 상태 추적을 명시적으로 활성화하려면
셀렉터 함수를 제공하거나 Subscribe HOC를 사용해야 합니다. 이렇게 하면 불필요한
재렌더링을 방지하고 컴포넌트가 업데이트되는 시점을 완전히 제어할 수 있습니다.
사용 가능한 상태 속성:
errorCount: 오류가 발생한 함수 실행 횟수isExecuting: 스로틀된 함수가 현재 비동기로 실행 중인지 여부isPending: 스로틀러가 실행을 트리거할 타임아웃을 기다리는지 여부lastArgs: 가장 최근 maybeExecute 호출의 인수lastExecutionTime: 마지막 함수 실행 시점의 타임스탬프(밀리초)lastResult: 가장 최근에 성공한 함수 실행 결과nextExecutionTime: 다음 실행이 가능한 시점의 타임스탬프(밀리초)settleCount: 성공 또는 오류로 완료된 함수 실행 횟수status: 현재 실행 상태('disabled' | 'idle' | 'pending' | 'executing' | 'settled')successCount: 성공적으로 완료된 함수 실행 횟수
언마운트 동작
기본적으로 컴포넌트가 언마운트되면 훅은 대기 중인 실행을 취소하고 진행 중인 실행을 중단합니다.
getAbortSignal()의 중단 신호를 내부 작업(예: fetch)에 전달한 경우에만 Abort가 해당 작업을 취소합니다.
이를 사용자 지정하려면 onUnmount 옵션을 사용합니다. 예를 들어 대기 중인 작업을 대신 플러시하려면 다음과 같이 합니다.
const throttler = useAsyncThrottler(fn, {
wait: 1000,
onUnmount: (t) => t.flush()
});
참고: 비동기 유틸리티에서 flush()는 Promise를 반환하며 정리 과정에서는 실행 후 결과를 기다리지 않습니다.
스로틀된 함수가 React 상태를 업데이트하면 해당 업데이트가 컴포넌트가
언마운트된 뒤 실행될 수 있으며, 이 경우 "setState on unmounted component" 경고가 발생할 수 있습니다. 콜백을
onUnmount에서 flush와 함께 사용할 때 적절히 보호해야 합니다.
타입 매개변수
TFn
TFn extends AnyAsyncFunction
TSelected
TSelected = {
}
매개변수
fn
TFn
options
ReactAsyncThrottlerOptions<TFn, TSelected>
selector
(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 }
);
// Subscribe to state changes deep in component tree using Subscribe HOC
<asyncThrottler.Subscribe selector={(state) => ({ isExecuting: state.isExecuting, isPending: state.isPending })}>
{({ isExecuting, isPending }) => (
<div>{isExecuting || isPending ? 'Loading...' : 'Ready'}</div>
)}
</asyncThrottler.Subscribe>
// Opt-in to re-render when execution state changes at hook level (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;