함수: useDebouncedState()
function useDebouncedState<TValue, TSelected>(
value,
options,
selector?): [TValue, Dispatch<StateUpdater<TValue>>, PreactDebouncer<Dispatch<StateUpdater<TValue>>, TSelected>];
정의 위치: preact-pacer/src/debouncer/useDebouncedState.ts:79
Preact의 useState와 디바운스 기능을 결합해 디바운스된 상태 값을 생성하는 Preact 훅입니다. 현재 디바운스된 값과 이를 업데이트하는 메서드를 모두 제공합니다.
상태 값은 마지막 업데이트 시도 후 지정된 대기 시간이 경과해야 업데이트됩니다. 대기 시간이 끝나기 전에 다른 업데이트를 시도하면 타이머가 초기화되고 다시 대기하기 시작합니다. 검색 입력 값이나 창 크기처럼 빈번하지만 스로틀해야 하는 상태 업데이트를 처리할 때 유용합니다.
훅은 다음 요소를 담은 튜플을 반환합니다.
- 현재 디바운스된 값
- 디바운스된 값을 업데이트하는 함수
- 추가 제어 메서드를 제공하는 디바운서 인스턴스
상태 관리와 셀렉터
훅은 내부 디바운서 인스턴스를 통해 반응형 상태 관리에 TanStack Store를 사용합니다.
selector 매개변수를 사용하면 디바운서 상태의 어떤 변경이 재렌더링을 트리거할지 지정할 수 있으며,
관련 없는 상태가 변경될 때 불필요한 재렌더링을 방지하여 성능을 최적화합니다.
기본적으로 반응형 상태 구독은 없습니다. 상태 추적을 명시적으로 활성화하려면 셀렉터 함수를 제공해야 합니다. 이렇게 하면 불필요한 재렌더링을 방지하고 컴포넌트 업데이트 시점을 완전히 제어할 수 있습니다. 셀렉터를 제공한 경우에만 선택한 상태 값이 변경될 때 컴포넌트가 다시 렌더링됩니다.
사용 가능한 디바운서 상태 속성:
canLeadingExecute: 디바운서가 선행 에지에서 실행될 수 있는지 여부executionCount: 완료된 함수 실행 횟수isPending: 디바운서가 실행을 트리거할 타임아웃을 기다리는지 여부lastArgs: 가장 최근 maybeExecute 호출의 인수status: 현재 실행 상태('disabled' | 'idle' | 'pending')
타입 매개변수
TValue
TValue
TSelected
TSelected = DebouncerState<Dispatch<StateUpdater<TValue>>>
매개변수
value
TValue
options
PreactDebouncerOptions<Dispatch<StateUpdater<TValue>>, TSelected>
selector?
(state) => TSelected
반환값
[TValue, Dispatch<StateUpdater<TValue>>, PreactDebouncer<Dispatch<StateUpdater<TValue>>, TSelected>]
예시
// Default behavior - no reactive state subscriptions
const [searchTerm, setSearchTerm, debouncer] = useDebouncedState('', {
wait: 500 // Wait 500ms after last keystroke
});
// Opt-in to re-render when pending state changes (optimized for loading indicators)
const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
'',
{ wait: 500 },
(state) => ({ isPending: state.isPending })
);
// Opt-in to re-render when execution count changes (optimized for tracking executions)
const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
'',
{ wait: 500 },
(state) => ({ executionCount: state.executionCount })
);
// Opt-in to re-render when debouncing status changes (optimized for status display)
const [searchTerm, setSearchTerm, debouncer] = useDebouncedState(
'',
{ wait: 500 },
(state) => ({
status: state.status,
canLeadingExecute: state.canLeadingExecute
})
);
// Update value - will be debounced
const handleChange = (e) => {
setSearchTerm(e.target.value);
};
// Access the selected debouncer state (will be empty object {} unless selector provided)
const { isPending, executionCount } = debouncer.state;