TanStack Pacer Preact 어댑터
Preact 애플리케이션에서는 Preact 어댑터를 사용합니다. 이 어댑터의 훅은 코어 Pacer 유틸리티를 수명 주기 정리 및 반응형 상태와 함께 래핑합니다. 또한 코어 패키지의 모든 항목을 다시 내보내므로 일반 클래스와 함수를 같은 위치에서 가져올 수 있습니다.
설치
npm install @tanstack/preact-pacer
Preact 훅
Preact 어댑터의 전체 훅 목록은 Preact 함수 레퍼런스를 참고합니다.
기본 사용법
Preact 어댑터에서 Preact 전용 훅을 가져옵니다.
import { useDebouncedValue } from '@tanstack/preact-pacer'
import { useState } from 'preact/hooks'
const [instantValue, setInstantValue] = useState(0)
const [debouncedValue, debouncer] = useDebouncedValue(instantValue, {
wait: 1000,
})
또는 Preact 어댑터가 다시 내보내는 코어 Pacer 클래스나 함수를 가져옵니다.
import { debounce, Debouncer } from '@tanstack/preact-pacer' // no need to install the core package separately
옵션 헬퍼
옵션 헬퍼는 전체 타입 검사를 지원하는 공유 옵션을 정의하므로 한 번 선언한 뒤 여러 훅에서 재사용할 수 있습니다.
디바운서 옵션
import { useDebouncer } from '@tanstack/preact-pacer'
import { debouncerOptions } from '@tanstack/pacer'
const commonDebouncerOptions = debouncerOptions({
wait: 1000,
leading: false,
trailing: true,
})
const debouncer = useDebouncer(
(query: string) => fetchSearchResults(query),
{ ...commonDebouncerOptions, key: 'searchDebouncer' }
)
비동기 큐어 옵션
import { useAsyncQueuer } from '@tanstack/preact-pacer'
import { asyncQueuerOptions } from '@tanstack/pacer'
const commonAsyncQueuerOptions = asyncQueuerOptions({
concurrency: 3,
addItemsTo: 'back',
})
const queuer = useAsyncQueuer(
async (item: string) => processItem(item),
{ ...commonAsyncQueuerOptions, key: 'itemQueuer' }
)
요청률 제한기 옵션
import { useRateLimiter } from '@tanstack/preact-pacer'
import { rateLimiterOptions } from '@tanstack/pacer'
const commonRateLimiterOptions = rateLimiterOptions({
limit: 5,
window: 60000,
windowType: 'sliding',
})
const rateLimiter = useRateLimiter(
(data: string) => sendApiRequest(data),
{ ...commonRateLimiterOptions, key: 'apiRateLimiter' }
)
프로바이더
PacerProvider 컴포넌트는 컴포넌트 트리에 있는 모든 Pacer 유틸리티 인스턴스의 기본 옵션을 설정합니다.
import { PacerProvider } from '@tanstack/preact-pacer'
// Set default options for preact-pacer instances
<PacerProvider
defaultOptions={{
debouncer: { wait: 1000 },
asyncQueuer: { concurrency: 3 },
rateLimiter: { limit: 5, window: 60000 },
}}
>
<App />
</PacerProvider>
프로바이더 내부의 훅은 이 기본값을 사용합니다. 개별 훅에 전달한 옵션은 기본값을 재정의합니다.
상태 구독하기
Preact 어댑터는 두 가지 방식으로 상태 변경 구독을 지원합니다.
Subscribe 컴포넌트 사용하기
훅에 셀렉터를 전달하지 않고 컴포넌트 트리 깊은 곳에서 상태를 읽으려면 Subscribe 컴포넌트를 사용합니다.
import { useRateLimiter } from '@tanstack/preact-pacer'
function ApiComponent() {
const rateLimiter = useRateLimiter(
(data: string) => {
return fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify({ data }),
})
},
{ limit: 5, window: 60000 }
)
return (
<div>
<button onClick={() => rateLimiter.maybeExecute('some data')}>
Submit
</button>
<rateLimiter.Subscribe selector={(state) => ({ rejectionCount: state.rejectionCount })}>
{({ rejectionCount }) => (
<div>Rejections: {rejectionCount}</div>
)}
</rateLimiter.Subscribe>
</div>
)
}
selector 매개변수 사용하기
selector 매개변수는 어떤 상태 변경이 반응형 업데이트를 트리거할지 제어합니다. 선택하지 않은 상태는 업데이트를 일으키지 않습니다.
셀렉터가 없으면 hook.state는 빈 객체({})입니다. 상태 추적을 사용하려면 셀렉터 함수를 전달합니다.
import { useDebouncer } from '@tanstack/preact-pacer'
function SearchComponent() {
// Default behavior - no reactive state subscriptions
const untrackedDebouncer = useDebouncer(
(query: string) => fetchSearchResults(query),
{ wait: 500 }
)
console.log(untrackedDebouncer.state) // {}
// Opt-in to track isPending changes
const debouncer = useDebouncer(
(query: string) => fetchSearchResults(query),
{ wait: 500 },
(state) => ({ isPending: state.isPending })
)
console.log(debouncer.state.isPending) // Reactive value
return (
<input
onChange={(e) => debouncer.maybeExecute(e.target.value)}
placeholder="Search..."
/>
)
}
상태 관리와 사용 가능한 상태 속성에 관한 자세한 내용은 각 유틸리티의 개별 가이드 페이지(예: 요청률 제한 가이드, 디바운싱 가이드)를 참고합니다.
예제
디바운서 예제
import { useDebouncer } from '@tanstack/preact-pacer'
function SearchComponent() {
const debouncer = useDebouncer(
(query: string) => {
console.log('Searching for:', query)
// Perform search
},
{ wait: 500 }
)
return (
<input
onChange={(e) => debouncer.maybeExecute(e.target.value)}
placeholder="Search..."
/>
)
}
비동기 큐어 예제
import { useAsyncQueuer } from '@tanstack/preact-pacer'
function UploadComponent() {
const queuer = useAsyncQueuer(
async (file: File) => {
await uploadFile(file)
},
{ concurrency: 3 }
)
const handleFileSelect = (files: FileList) => {
Array.from(files).forEach((file) => {
queuer.addItem(file)
})
}
return (
<input
type="file"
multiple
onChange={(e) => {
if (e.target.files) {
handleFileSelect(e.target.files)
}
}}
/>
)
}
요청률 제한기 예제
import { useRateLimiter } from '@tanstack/preact-pacer'
function ApiComponent() {
const rateLimiter = useRateLimiter(
(data: string) => {
return fetch('/api/endpoint', {
method: 'POST',
body: JSON.stringify({ data }),
})
},
{
limit: 5,
window: 60000,
windowType: 'sliding',
onReject: () => {
alert('Rate limit reached. Please try again later.')
},
}
)
const handleSubmit = () => {
const remaining = rateLimiter.getRemainingInWindow()
if (remaining > 0) {
rateLimiter.maybeExecute('some data')
}
}
return <button onClick={handleSubmit}>Submit</button>
}