본문으로 건너뛰기

함수: useBatcher()

function useBatcher<TValue, TSelected>(
fn,
options,
selector): PreactBatcher<TValue, TSelected>;

정의 위치: preact-pacer/src/batcher/useBatcher.ts:183

Batcher 인스턴스를 생성하고 관리하는 Preact 훅입니다.

내장 상태 관리 없이 Batcher의 기능에 직접 접근할 수 있는 하위 수준 훅입니다. 따라서 onItemsChange 콜백을 활용하여 선호하는 어떤 상태 관리 솔루션 (useState, Redux, Zustand 등)과도 통합할 수 있습니다.

Batcher는 구성 가능한 다음 조건에 따라 항목을 모아 배치로 처리합니다.

  • 최대 배치 크기
  • 시간 기반 배칭(X밀리초 후 처리)
  • getShouldExecute를 통한 사용자 지정 배치 처리 로직

상태 관리와 셀렉터

훅은 반응형 상태 관리에 TanStack Store를 사용합니다. 다음 두 가지 방식으로 상태 변경을 구독할 수 있습니다.

1. batcher.Subscribe HOC 사용(컴포넌트 트리 구독에 권장)

Subscribe HOC를 사용하면 컴포넌트 트리 깊은 곳의 상태 변경을 구독할 때 훅에 셀렉터를 전달할 필요가 없습니다. 자식 컴포넌트에서 상태를 구독하려는 경우에 적합합니다.

2. selector 매개변수 사용(훅 수준 구독)

selector 매개변수를 사용하면 어떤 상태 변경이 재렌더링을 트리거할지 지정할 수 있으며 관련 없는 상태가 변경될 때 불필요한 재렌더링을 방지하여 훅 수준의 성능을 최적화합니다.

기본적으로 반응형 상태 구독은 없습니다. 상태 추적을 명시적으로 활성화하려면 셀렉터 함수를 제공하거나 Subscribe HOC를 사용해야 합니다. 이렇게 하면 불필요한 재렌더링을 방지하고 컴포넌트가 업데이트되는 시점을 완전히 제어할 수 있습니다.

사용 가능한 상태 속성:

  • executionCount: 완료된 배치 실행 횟수
  • isEmpty: 배처에 처리할 항목이 없는지 여부
  • isPending: 배처가 배치 처리를 트리거할 타임아웃을 기다리는지 여부
  • isRunning: 배처가 활성 상태이며 항목을 자동으로 처리할지 여부
  • items: 현재 배치 처리 대기 중인 항목 배열
  • size: 현재 배치 큐에 있는 항목 수
  • status: 현재 처리 상태('idle' | 'pending')
  • totalItemsProcessed: 모든 배치에서 처리된 전체 항목 수

언마운트 동작

기본적으로 컴포넌트가 언마운트되면 훅은 대기 중인 배치를 취소합니다. 이를 사용자 지정하려면 onUnmount 옵션을 사용합니다. 예를 들어 대기 중인 작업을 대신 플러시하려면 다음과 같이 합니다.

const batcher = useBatcher(fn, {
maxSize: 10,
wait: 2000,
onUnmount: (b) => b.flush()
});

타입 매개변수

TValue

TValue

TSelected

TSelected = { }

매개변수

fn

(items) => void

options

PreactBatcherOptions&lt;TValue, TSelected> = {}

selector

(state) => TSelected

반환값

PreactBatcher&lt;TValue, TSelected>

예시

// Default behavior - no reactive state subscriptions
const batcher = useBatcher<number>(
(items) => console.log('Processing batch:', items),
{ maxSize: 5, wait: 2000 }
);

// Subscribe to state changes deep in component tree using Subscribe HOC
<batcher.Subscribe selector={(state) => ({ size: state.size })}>
{({ size }) => (
<div>Batch Size: {size}</div>
)}
</batcher.Subscribe>

// Opt-in to re-render when batch size changes at hook level (optimized for displaying queue size)
const batcher = useBatcher<number>(
(items) => console.log('Processing batch:', items),
{ maxSize: 5, wait: 2000 },
(state) => ({
size: state.size,
isEmpty: state.isEmpty
})
);

// Opt-in to re-render when execution metrics change (optimized for stats display)
const batcher = useBatcher<number>(
(items) => console.log('Processing batch:', items),
{ maxSize: 5, wait: 2000 },
(state) => ({
executionCount: state.executionCount,
totalItemsProcessed: state.totalItemsProcessed
})
);

// Opt-in to re-render when processing state changes (optimized for loading indicators)
const batcher = useBatcher<number>(
(items) => console.log('Processing batch:', items),
{ maxSize: 5, wait: 2000 },
(state) => ({
isPending: state.isPending,
isRunning: state.isRunning,
status: state.status
})
);

// Example with custom state management and batching
const [items, setItems] = useState([]);

const batcher = useBatcher<number>(
(items) => console.log('Processing batch:', items),
{
maxSize: 5,
wait: 2000,
onItemsChange: (batcher) => setItems(batcher.peekAllItems()),
getShouldExecute: (items) => items.length >= 3
}
);

// Add items to batch - they'll be processed when conditions are met
batcher.addItem(1);
batcher.addItem(2);
batcher.addItem(3); // Triggers batch processing

// Control the batcher
batcher.stop(); // Pause batching
batcher.start(); // Resume batching

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