본문으로 건너뛰기

함수: useThrottledValue()

function useThrottledValue<TValue, TSelected>(
value,
options,
selector?): [TValue, ReactThrottler<Dispatch<SetStateAction<TValue>>, TSelected>];

정의 위치: react-pacer/src/throttler/useThrottledValue.ts:82

지정된 시간 윈도우 안에서 최대 한 번 업데이트되는 스로틀 값 버전을 생성하는 상위 수준 React 훅입니다. 이 훅은 내부적으로 React의 useState를 사용해 스로틀된 상태를 관리합니다.

스로틀은 입력 값의 변경 빈도와 관계없이 값이 제어된 속도로 업데이트되도록 합니다. 빠르게 변하는 값에 의존하는 비용이 큰 재렌더링이나 API 호출의 요청률을 제한할 때 유용합니다.

훅은 다음 요소를 담은 튜플을 반환합니다.

  • 옵션에 지정된 선행/후행 에지 동작에 따라 업데이트되는 스로틀 값
  • 제어 메서드를 제공하는 스로틀러 인스턴스

React 상태 관리 없이 스로틀 동작을 더 직접 제어하려면 하위 수준 useThrottler 훅을 대신 사용합니다.

상태 관리와 셀렉터​

훅은 내부 스로틀러 인스턴스를 통해 반응형 상태 관리에 TanStack Store를 사용합니다. selector 매개변수를 사용하면 스로틀러 상태의 어떤 변경이 재렌더링을 트리거할지 지정할 수 있으며, 관련 없는 상태가 변경될 때 불필요한 재렌더링을 방지하여 성능을 최적화합니다.

기본적으로 반응형 상태 구독은 없습니다. 상태 추적을 명시적으로 활성화하려면 셀렉터 함수를 제공해야 합니다. 이렇게 하면 불필요한 재렌더링을 방지하고 컴포넌트 업데이트 시점을 완전히 제어할 수 있습니다. 셀렉터를 제공한 경우에만 선택한 상태 값이 변경될 때 컴포넌트가 다시 렌더링됩니다.

사용 가능한 스로틀러 상태 속성:

  • executionCount: 완료된 함수 실행 횟수
  • lastArgs: 가장 최근 maybeExecute 호출의 인수
  • lastExecutionTime: 마지막 함수 실행 시점의 타임스탬프(밀리초)
  • nextExecutionTime: 다음 실행이 가능한 시점의 타임스탬프(밀리초)
  • isPending: 스로틀러가 실행을 트리거할 타임아웃을 기다리는지 여부
  • status: 현재 실행 상태('disabled' | 'idle' | 'pending')

타입 매개변수​

TValue​

TValue

TSelected​

TSelected = ThrottlerState&lt;Dispatch&lt;SetStateAction&lt;TValue>>>

매개변수​

value​

TValue

options​

ReactThrottlerOptions&lt;Dispatch&lt;SetStateAction&lt;TValue>>, TSelected>

selector?​

(state) => TSelected

반환값​

[TValue, ReactThrottler&lt;Dispatch&lt;SetStateAction&lt;TValue>>, TSelected>]

예시​

// Default behavior - no reactive state subscriptions
const [throttledValue, throttler] = useThrottledValue(rawValue, { wait: 1000 });

// Opt-in to re-render when execution count changes (optimized for tracking executions)
const [throttledValue, throttler] = useThrottledValue(
rawValue,
{ wait: 1000 },
(state) => ({ executionCount: state.executionCount })
);

// Opt-in to re-render when throttling state changes (optimized for loading indicators)
const [throttledValue, throttler] = useThrottledValue(
rawValue,
{ wait: 1000 },
(state) => ({
isPending: state.isPending,
status: state.status
})
);

// Opt-in to re-render when timing information changes (optimized for timing displays)
const [throttledValue, throttler] = useThrottledValue(
rawValue,
{ wait: 1000 },
(state) => ({
lastExecutionTime: state.lastExecutionTime,
nextExecutionTime: state.nextExecutionTime
})
);

// With custom leading/trailing behavior
const [throttledValue, throttler] = useThrottledValue(rawValue, {
wait: 1000,
leading: true, // Update immediately on first change
trailing: false // Skip trailing edge updates
});

// Access the selected throttler state (will be empty object {} unless selector provided)
const { executionCount, isPending } = throttler.state;