### Initialize App with Rate Limiter Example Source: https://tanstack.com/pacer/latest/docs/framework/vanilla/examples/LiteRateLimiter Appends the created rate limiter example UI to the DOM. This is the entry point for the example. ```javascript const app = document.getElementById('app')! app.appendChild(createApp1()) console.log( 'LiteRateLimiter example ready! Click increment rapidly and watch the console for rate limited executions.', ) ``` -------------------------------- ### Starting Queue Processing Source: https://tanstack.com/pacer/latest/docs/framework/react/reference/functions/useQueuedState.md Shows how to manually start the automatic processing of the queue using the `start` method on the queue object. ```tsx // Start automatic processing const startProcessing = () => { queue.start(); }; ``` -------------------------------- ### Initialize and Run LiteBatcher Example Source: https://tanstack.com/pacer/latest/docs/framework/vanilla/examples/LiteBatcher Sets up the LiteBatcher, defines functions for batch operations (add, flush, clear, cancel), and updates the UI to reflect the batch state. This is the main function to create and render the example. ```javascript function createApp1() { const container = document.createElement('div') let batchesProcessed = 0 let totalItemsProcessed = 0 let processedBatches = [] const batcher = new LiteBatcher({ maxBatchSize: 5, onBatch: (batch) => { batchesProcessed++ totalItemsProcessed += batch.length processedBatches.push(batch) console.log('⚡ Processed batch:', batch) updateDisplay() }, }) function addItem() { const newItem = Math.random().toString(36).substring(2, 9) batcher.push(newItem) console.log('➕ Added item:', newItem) updateDisplay() } function flushBatch() { batcher.flush() console.log('⚡ Flushed current batch') updateDisplay() } function clearBatch() { batcher.clear() console.log('🔄 Batch cleared') updateDisplay() } function cancelPending() { batcher.cancel() console.log('❌ Cancelled pending batch') updateDisplay() } function updateDisplay() { const batchSize = batcher.size const isEmpty = batcher.isEmpty const isPending = batcher.isPending const batchItems = batcher.peekAllItems() container.innerHTML = `

TanStack Pacer LiteBatcher Example

Batch Size: ${batchSize}
Batch Max Size: 5
Batch Items: ${batchItems.length > 0 ? batchItems.join(', ') : 'None'}
Is Pending: ${isPending ? 'Yes' : 'No'}
Batches Processed: ${batchesProcessed}
Items Processed: ${totalItemsProcessed}
Processed Batches: ${processedBatches.length > 0 ? processedBatches.map((b) => `[${b.join(', ')}]`).join(', ') : 'None'}
` container.querySelector('#add-item-btn')?.addEventListener('click', addItem) container.querySelector('#flush-btn')?.addEventListener('click', flushBatch) container.querySelector('#clear-btn')?.addEventListener('click', clearBatch) container .querySelector('#cancel-btn') ?.addEventListener('click', cancelPending) } updateDisplay() return container } const app = document.getElementById('app')! app.appendChild(createApp1()) console.log( 'LiteBatcher example ready! Add items and watch them batch automatically, or use flush to process immediately.', ) ``` -------------------------------- ### Initialize and Use AsyncQueuer Source: https://tanstack.com/pacer/latest/docs/reference/classes/AsyncQueuer.md Example of creating an AsyncQueuer instance with a processing function and options, then adding an item and starting the queue. The onSuccess callback logs the result of the processed item. ```typescript const asyncQueuer = new AsyncQueuer((item) => { // process item return item.toUpperCase(); }, { concurrency: 2, onSuccess: (result) => { console.log(result); } }); asyncQueuer.addItem('hello'); asyncQueuer.start(); ``` -------------------------------- ### asyncDebounce Example Usage Source: https://tanstack.com/pacer/latest/docs/reference/functions/asyncDebounce.md A practical example demonstrating how to use the asyncDebounce function with error handling and retrieving results. ```APIDOC ## Example ```ts const debounced = asyncDebounce(async (value: string) => { const result = await saveToAPI(value); return result; // Return value is preserved }, { wait: 1000, onError: (error) => { console.error('API call failed:', error); }, throwOnError: true // Will both log the error and throw it }); // Will only execute once, 1 second after the last call // Returns the API response directly const result = await debounced("third"); ``` ``` -------------------------------- ### started Option Source: https://tanstack.com/pacer/latest/docs/reference/interfaces/AsyncQueuerOptions.md Determines whether the queuer should start processing tasks immediately. ```APIDOC ## started ### Description Whether the queuer should start processing tasks immediately or not. ### Parameters #### Path Parameters - **started** (boolean) - Optional - If true, the queuer starts processing immediately. ``` -------------------------------- ### Install Solid Devtools Adapter Source: https://tanstack.com/pacer/latest/docs/installation.md Install the Solid devtools adapter and Pacer devtools plugin as dev dependencies. ```bash npm install @tanstack/solid-devtools @tanstack/solid-pacer-devtools --save-dev ``` -------------------------------- ### Install Solid Pacer Devtools Source: https://tanstack.com/pacer/latest/docs/devtools.md Install the necessary packages for Solid Pacer Devtools using npm. ```sh npm install @tanstack/solid-devtools @tanstack/solid-pacer-devtools ``` -------------------------------- ### Install Solid Pacer Adapter Source: https://tanstack.com/pacer/latest/docs/installation.md Install the Solid adapter for TanStack Pacer using npm, yarn, or pnpm. ```bash npm install @tanstack/solid-pacer ``` -------------------------------- ### Pre-populate Queue with Initial Items Source: https://tanstack.com/pacer/latest/docs/guides/queuing.md Initialize the queue with a list of items and optionally start processing immediately by setting `started: true`. ```typescript const queue = new Queuer( (item) => { // Process each item console.log('Processing:', item) }, { initialItems: [1, 2, 3], started: true // Start processing immediately } ) ``` -------------------------------- ### LiteThrottler Example Ready Message Source: https://tanstack.com/pacer/latest/docs/framework/vanilla/examples/LiteThrottler Logs a message to the console indicating that the LiteThrottler example is ready. It suggests interacting with buttons to observe throttled executions. ```javascript console.log( 'LiteThrottler example ready! Click the buttons rapidly and watch the console for throttled executions.', ) ``` -------------------------------- ### React Query Queued Prefetch Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/batch This example demonstrates using a queue with `prefetchQuery` in React Query. It ensures that prefetch requests are executed sequentially, which can be useful if the order of prefetching matters or if there are dependencies between prefetches. ```javascript import React from "react"; import { useQueryClient } from "@tanstack/react-query"; import { queue } from "@tanstack/pacer"; function SequentialPrefetchComponent() { const queryClient = useQueryClient(); const prefetchQueue = React.useMemo(() => queue(), [queryClient]); const addPrefetchTask = (queryKey, queryFn) => { prefetchQueue.add(async () => { await queryClient.prefetchQuery({ queryKey, queryFn }); console.log(`Prefetched: ${queryKey}`); }); }; const handlePrefetchSequence = () => { addPrefetchTask(['user', 1], async () => 'User 1 data'); addPrefetchTask(['user', 2], async () => 'User 2 data'); addPrefetchTask(['settings'], async () => 'App settings'); }; return ( ); } ``` -------------------------------- ### React Query Debounced Prefetch Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/react-query-debounced-prefetch This is the main example component. It sets up React Query, fetches a list of posts, and uses a debounced value to prefetch individual post details on hover. Requires `react-query` and `react-pacer`. ```typescript import React, { useEffect } from 'react' import ReactDOM from 'react-dom/client' import { QueryClient, QueryClientProvider, useQuery, } from '@tanstack/react-query' import { ReactQueryDevtools } from '@tanstack/react-query-devtools' import { useDebouncedValue } from '@tanstack/react-pacer' // Fetch all posts const fetchPosts = async () => { const response = await fetch('https://jsonplaceholder.typicode.com/posts') return response.json() } // Fetch a single post const fetchPost = async (id: number) => { await new Promise((resolve) => setTimeout(resolve, 1000)) // Simulate a slow response const response = await fetch( `https://jsonplaceholder.typicode.com/posts/${id}`, ) return response.json() } function PostList({ setSelectedPostId, }: { setSelectedPostId: (id: number) => void }) { // Simple query that fetches all posts const { data: posts, isLoading } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts, }) // keep track of the hovered post id that could be prefetched const [currentHoveredPostId, setCurrentHoveredPostId] = React.useState< number | null >(null) // debounce the hovered post id to avoid excessive prefetches const [debouncedHoveredPostId] = useDebouncedValue(currentHoveredPostId, { wait: 100, // adjust this value to see the difference // Alternative to debouncer.Subscribe: pass a selector as 3rd arg to cause re-renders and subscribe to state // (state) => state, }) // perform the prefetch when the debounced hovered post id changes useEffect(() => { if (debouncedHoveredPostId) { queryClient.ensureQueryData({ queryKey: ['post', debouncedHoveredPostId], queryFn: () => fetchPost(debouncedHoveredPostId), }) } }, [debouncedHoveredPostId]) const handleMouseEnter = (postId: number) => { setCurrentHoveredPostId(postId) // update the hovered post id } if (isLoading) return
Loading posts...
return (

Posts

) } function PostDetail({ postId }: { postId: number }) { const { data: post, isLoading } = useQuery({ queryKey: ['post', postId], queryFn: () => fetchPost(postId), }) if (isLoading) return
Loading post...
return (

{post?.title}

{post?.body}

) } function App() { const [selectedPostId, setSelectedPostId] = React.useState( null, ) return (

TanStack Pacer/Query Debounced Prefetch Example

Hover over a post title to prefetch its content

This example shows how to prefetch a query when the user hovers over a post.

The debounced query key is created after a debounce to avoid excessive prefetches.

{selectedPostId && }
) } const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 10_000, }, }, }) const root = ReactDOM.createRoot(document.getElementById('root')!) root.render( , ) ``` -------------------------------- ### React Query Queued Prefetch Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/asyncRateLimit This example demonstrates using a queue with TanStack Query's prefetch. It ensures that prefetch requests are executed sequentially, which can be important if prefetching multiple related data sets. ```javascript import React from "react"; import { useQueryClient } from "@tanstack/react-query"; import { queue } from "@tanstack/pacer"; import { useQueuer } from "@tanstack/react-pacer"; function QueuedPrefetch() { const queryClient = useQueryClient(); const { enqueue } = useQueuer(); const prefetchData = async (id) => { console.log(`Prefetching data for ID: ${id}`); await queryClient.prefetchQuery({ queryKey: ["item", id], queryFn: async () => { const response = await fetch(`/api/items/${id}`); return response.json(); }, }); console.log(`Prefetch complete for ID: ${id}`); }; const handlePrefetchBatch = () => { enqueue(() => prefetchData(1)); enqueue(() => prefetchData(2)); enqueue(() => prefetchData(3)); console.log("Prefetch tasks enqueued. They will run sequentially."); }; return (
); } ``` -------------------------------- ### React Query Queued Prefetch Example Source: https://tanstack.com/pacer/latest/docs/framework/vanilla/examples/LiteQueuer This example illustrates using TanStack Pacer's queuing mechanism with React Query prefetching. It ensures that prefetch requests are executed in the order they are initiated, maintaining a predictable sequence. ```javascript import React from 'react'; import { useQueryClient } from '@tanstack/react-query'; import { queue } from '@tanstack/pacer'; function QueuedPrefetchComponent() { const queryClient = useQueryClient(); const prefetchQueue = queue(); const addPrefetchTask = (queryKey, queryFn) => { prefetchQueue.add(() => { console.log(`Prefetching: ${queryKey[0]}`); return queryClient.prefetchQuery({ queryKey, queryFn }); }); }; const handlePrefetchClick = (id) => { addPrefetchTask(['data', id], () => fetchData(id)); }; // Assume fetchData is defined elsewhere const fetchData = async (id) => { // ... fetch data logic ... return `Data for ${id}`; }; return (

Prefetches will execute in order.

); } export default QueuedPrefetchComponent; ``` -------------------------------- ### Dynamically Configure Queuer Options Source: https://tanstack.com/pacer/latest/docs/guides/queuing.md Modify queue options like `wait` and `started` after creation using `setOptions()`. This example changes the processing speed and starts the queue. ```typescript const queue = new Queuer( (item) => { // Process each item console.log('Processing:', item) }, { wait: 1000, started: false } ) // Change configuration queue.setOptions({ wait: 500, // Process items twice as fast started: true // Start processing }) // Access current state console.log(queue.store.state.size) // Current queue size console.log(queue.store.state.isRunning) // Whether queue is running ``` -------------------------------- ### Initialize and Append App Source: https://tanstack.com/pacer/latest/docs/framework/vanilla/examples/liteBatch This snippet demonstrates initializing an application and appending it to the DOM. It logs a message indicating the 'liteBatch example' is ready. ```javascript const app = document.getElementById('app')! app.appendChild(createApp1()) console.log( 'liteBatch example ready! Add items and watch them batch automatically.', ) ``` -------------------------------- ### React useAsyncRateLimiter Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/useAsyncRateLimiter This example demonstrates how to use the `useAsyncRateLimiter` hook to limit the rate of API calls in a React component. It includes setup for both fixed and sliding window types, error handling, and subscription to rate limiter state. ```tsx import { useEffect, useState } from 'react' import ReactDOM from 'react-dom/client' import { useAsyncRateLimiter } from '@tanstack/react-pacer/async-rate-limiter' import { PacerProvider } from '@tanstack/react-pacer/provider' interface SearchResult { id: number title: string } // Simulate API call with fake data const fakeApi = async (term: string): Promise> => { await new Promise((resolve) => setTimeout(resolve, 300)) // Simulate network delay return [ { id: 1, title: `${term} result ${Math.floor(Math.random() * 100)}` }, { id: 2, title: `${term} result ${Math.floor(Math.random() * 100)}` }, { id: 3, title: `${term} result ${Math.floor(Math.random() * 100)}` }, ] } function App() { const [windowType, setWindowType] = useState<'fixed' | 'sliding'>('fixed') const [searchTerm, setSearchTerm] = useState('') const [results, setResults] = useState>([]) const [error, setError] = useState(null) // The function that will become rate limited const handleSearch = async (term: string) => { if (!term) { setResults([]) return } // throw new Error('Test error') // you don't have to catch errors here (though you still can). The onError optional handler will catch it const data = await fakeApi(term) setResults(data) setError(null) } // hook that gives you an async rate limiter instance const setSearchAsyncRateLimiter = useAsyncRateLimiter( handleSearch, { windowType: windowType, limit: 3, // Maximum 2 requests window: 3000, // per 1 second onReject: (_args, rateLimiter) => { console.log( `Rate limit reached. Try again in ${rateLimiter.getMsUntilNextWindow()}ms`, ) }, onError: (error) => { // optional error handler console.error('Search failed:', error) setError(error as Error) setResults([]) }, }, // Alternative to setSearchAsyncRateLimiter.Subscribe: pass a selector as 3rd arg to cause re-renders and subscribe to state // (state) => state, ) // get and name our rate limited function const handleSearchRateLimited = setSearchAsyncRateLimiter.maybeExecute useEffect(() => { console.log('mount') return () => { console.log('unmount') setSearchAsyncRateLimiter.reset() // cancel any pending async calls when the component unmounts } }, []) // instant event handler that calls both the instant local state setter and the rate limited function async function onSearchChange(e: React.ChangeEvent) { const newTerm = e.target.value setSearchTerm(newTerm) await handleSearchRateLimited(newTerm) // optionally await if you need to } return (

TanStack Pacer useAsyncRateLimiter Example

{error &&
Error: {error.message}
} ({ successCount: state.successCount, rejectionCount: state.rejectionCount, isExecuting: state.isExecuting, })} > {({ successCount, rejectionCount, isExecuting }) => (
API calls made: {successCount}
Rejected calls: {rejectionCount}
Is executing: {isExecuting ? 'Yes' : 'No'}
Results: {results.length > 0 ? (
    {results.map((item) => ( ``` -------------------------------- ### Get Default Pacer Options Source: https://tanstack.com/pacer/latest/docs/framework/react/reference/functions/useDefaultPacerOptions.md Call this function to retrieve the default configuration options for the PacerProvider. No setup or imports are required. ```typescript function useDefaultPacerOptions(): PacerProviderOptions; ``` -------------------------------- ### Default useQueuedState Behavior Source: https://tanstack.com/pacer/latest/docs/framework/react/reference/functions/useQueuedState.md This example shows the default behavior of useQueuedState without explicit state subscriptions. It initializes with items and starts processing automatically. ```tsx // Default behavior - no reactive state subscriptions const [items, addItem, queue] = useQueuedState( (item) => console.log('Processing:', item), { initialItems: ['item1', 'item2'], started: true, wait: 1000, getPriority: (item) => item.priority } ); ``` -------------------------------- ### React useAsyncBatcher Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/useAsyncBatcher Demonstrates setting up and using the `useAsyncBatcher` hook with various configuration options like maxSize, wait, getShouldExecute, throwOnError, onSuccess, onError, and onSettled. It also shows how to add items, peek at the current batch, and manually flush the batch. ```typescript import { useState } from 'react' import ReactDOM from 'react-dom/client' import { useAsyncBatcher } from '@tanstack/react-pacer/async-batcher' import { PacerProvider } from '@tanstack/react-pacer/provider' const fakeProcessingTime = 1000 type Item = { id: number value: string timestamp: number } function App() { const [processedBatches, setProcessedBatches] = useState< Array<{ items: Array; result: string; timestamp: number }> >([]) const [errors, setErrors] = useState>([]) // The async function that will process a batch of items async function processBatch(items: Array): Promise { console.log('Processing batch of', items.length, 'items:', items) // Simulate async processing time await new Promise((resolve) => setTimeout(resolve, fakeProcessingTime)) // Simulate occasional failures for demo purposes // throw new Error(`Processing failed for batch with ${items.length} items`) // Return a result from the batch processing const result = `Processed ${items.length} items: ${items.map((item) => item.value).join(', ')}` setProcessedBatches((prev) => [ ...prev, { items, result, timestamp: Date.now() }, ]) return result } const asyncBatcher = useAsyncBatcher( processBatch, { maxSize: 5, // Process in batches of 5 (if reached before wait time) wait: 4000, // Wait up to 4 seconds before processing a batch getShouldExecute: (items) => items.some((item) => item.value.includes('urgent')), // Process immediately if any item is marked urgent throwOnError: false, // Don't throw errors, handle them via onError onSuccess: (result, batch, batcher) => { console.log('Batch succeeded:', result) console.log('Processed batch:', batch) console.log( 'Total successful batches:', batcher.store.state.successCount, ) }, onError: (error: any, _batcher) => { console.error('Batch failed:', error) setErrors((prev) => [ ...prev, `Error: ${error} (${new Date().toLocaleTimeString()})`, ]) }, onSettled: (batch, batcher) => { console.log('Batch settled:', batch) console.log( 'Total processed items:', batcher.store.state.totalItemsProcessed, ) }, }, // Alternative to asyncBatcher.Subscribe: pass a selector as 3rd arg to cause re-renders and subscribe to state // (state) => state, ) const addItem = (isUrgent = false) => { const nextId = Date.now() const item: Item = { id: nextId, value: isUrgent ? `urgent-${nextId}` : `item-${nextId}`, timestamp: nextId, } asyncBatcher.addItem(item) } const executeCurrentBatch = async () => { try { const result = await asyncBatcher.flush() console.log('Manual execution result:', result) } catch (error) { console.error('Manual execution failed:', error) } } return (

    TanStack Pacer useAsyncBatcher Example

    ({ size: state.size, isExecuting: state.isExecuting, status: state.status, successCount: state.successCount, errorCount: state.errorCount, totalItemsProcessed: state.totalItemsProcessed, })} > {({ size, isExecuting, status, successCount, errorCount, totalItemsProcessed, }) => (

    Batch Status

    Current Batch Size: {size}
    Max Batch Size: 5
    Is Executing: {isExecuting ? 'Yes' : 'No'}
    Status: {status}
    Successful Batches: {successCount}
    Failed Batches: {errorCount}
    Total Items Processed: {totalItemsProcessed}
    )}

    Current Batch Items

    {asyncBatcher.peekAllItems().length === 0 ? ( No items in current batch ) : ( asyncBatcher.peekAllItems().map((item, index) => (
    {index + 1}: {item.value} (added at{' '} {new Date(item.timestamp).toLocaleTimeString()})
    )) )}

    Controls

    { const response = await fetch('https://jsonplaceholder.typicode.com/posts') return response.json() } // Fetch a single post const fetchPost = async (id: number) => { await new Promise((resolve) => setTimeout(resolve, 1000)) // Simulate a slow response const response = await fetch( `https://jsonplaceholder.typicode.com/posts/${id}`, ) return response.json() } function PostList({ setSelectedPostId, }: { setSelectedPostId: (id: number) => void }) { // Simple query that fetches all posts const { data: posts, isLoading } = useQuery({ queryKey: ['posts'], queryFn: fetchPosts, }) // keep track of the hovered post id that could be prefetched const [currentHoveredPostId, setCurrentHoveredPostId] = React.useState< number | null >(null) // throttle the hovered post id to avoid excessive prefetches const [throttledHoveredPostId] = useThrottledValue(currentHoveredPostId, { wait: 100, // adjust this value to see the difference // Alternative to throttler.Subscribe: pass a selector as 3rd arg to cause re-renders and subscribe to state // (state) => state, }) // perform the prefetch when the throttled hovered post id changes useEffect(() => { if (throttledHoveredPostId) { queryClient.ensureQueryData({ queryKey: ['post', throttledHoveredPostId], queryFn: () => fetchPost(throttledHoveredPostId), }) } }, [throttledHoveredPostId]) const handleMouseEnter = (postId: number) => { setCurrentHoveredPostId(postId) // update the hovered post id } if (isLoading) return
    Loading posts...
    return ( ) } function PostDetail({ postId }: { postId: number }) { const { data: post, isLoading } = useQuery({ queryKey: ['post', postId], queryFn: () => fetchPost(postId), }) if (isLoading) return
    Loading post...
    return (

    {post?.title}

    {post?.body}

    ) } function App() { const [selectedPostId, setSelectedPostId] = React.useState( null, ) return (

    TanStack Pacer/Query Throttled Prefetch Example

    Hover over a post title to prefetch its content

    This example shows how to prefetch a query when the user hovers over a post.

    The throttled query key is created after a throttle to avoid excessive prefetches.

    {selectedPostId && }
    ) } const queryClient = new QueryClient({ defaultOptions: { queries: { staleTime: 10_000, }, }, }) const root = ReactDOM.createRoot(document.getElementById('root')!) root.render( , ) ``` -------------------------------- ### AsyncRateLimiter Example Usage Source: https://tanstack.com/pacer/latest/docs/reference/classes/AsyncRateLimiter.md Demonstrates how to create and use an AsyncRateLimiter instance. ```APIDOC ## Example ```ts const rateLimiter = new AsyncRateLimiter( async (id: string) => await api.getData(id), { limit: 5, window: 1000, windowType: 'sliding', onError: (error) => { console.error('API call failed:', error); }, onReject: (limiter) => { console.log(`Rate limit exceeded. Try again in ${limiter.getMsUntilNextWindow()}ms`); } } ); // Will execute immediately until limit reached, then block // Returns the API response directly const data = await rateLimiter.maybeExecute('123'); ``` ``` -------------------------------- ### Initialize useRateLimiter with Persister and State Subscription Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/useRateLimiterWithPersister Demonstrates initializing useRateLimiter with a local storage persister and subscribing to state changes using a selector. Includes options for window type and rejection handling. ```javascript import { useEffect, useState } from 'react' import ReactDOM from 'react-dom/client' import { useRateLimiter } from '@tanstack/react-pacer/rate-limiter' import { useStoragePersister } from '@tanstack/react-persister/storage-persister' import type { RateLimiterState } from '@tanstack/react-pacer/rate-limiter' function App1() { const [windowType, setWindowType] = useState<'fixed' | 'sliding'>('fixed') // Use your state management library of choice const [instantCount, setInstantCount] = useState(0) // not rate-limited const [limitedCount, setLimitedCount] = useState(0) // rate-limited const rateLimiterPersister = useStoragePersister({ key: 'my-rate-limiter', storage: localStorage, maxAge: 1000 * 60, // 1 minute buster: 'v1', }) // Using useRateLimiter with a rate limit of 5 executions per 5 seconds const rateLimiter = useRateLimiter( setLimitedCount, { // enabled: () => instantCount > 2, limit: 5, window: 5000, windowType: windowType, onReject: (rateLimiter) => console.log( 'Rejected by rate limiter', rateLimiter.getMsUntilNextWindow(), ), // optional local storage persister to retain state on page refresh initialState: rateLimiterPersister.loadState(), }, // Alternative to rateLimiter.Subscribe: pass a selector as 3rd arg to cause re-renders and subscribe to state // (state) => state, ) useEffect(() => { rateLimiterPersister.saveState(rateLimiter.store.state) }, [rateLimiter.store.state]) function increment() { // this pattern helps avoid common bugs with stale closures and state setInstantCount((c) => { const newCount = c + 1 // common new value for both rateLimiter.maybeExecute(newCount) // rate-limited state update return newCount // instant state update }) } return (

    TanStack Pacer useRateLimiter Example 1 (with persister)

    ({ executionCount: state.executionCount, rejectionCount: state.rejectionCount, })} > {({ executionCount, rejectionCount }) => ( <> ``` -------------------------------- ### Use Throttled Value Hook Example Source: https://tanstack.com/pacer/latest/docs/framework The `useThrottledValue` hook is a direct hook to get a throttled version of an input value. It updates at most once per the specified interval. ```javascript import React from 'react' import { useThrottledValue } from "@tanstack/react-pacer" function MyComponent() { const [inputValue, setInputValue] = React.useState('') const throttledInputValue = useThrottledValue(inputValue, 500) return (
    setInputValue(e.target.value)} />

    Throttled Input Value: {throttledInputValue}

    ) } ``` -------------------------------- ### Async Queue Function Example Source: https://tanstack.com/pacer/latest/docs/framework/react/examples/react-query-throttled-prefetch The asyncQueue function is designed for managing asynchronous tasks in a sequential queue. It ensures that each async task completes before the next one starts. ```javascript import { asyncQueue } from "@tanstack/pacer" const asyncTaskQueue = asyncQueue() const asyncTask1 = async () => { await new Promise(resolve => setTimeout(resolve, 1200)) console.log('Async Task 1 done') return 'Data from task 1' } const asyncTask2 = async () => { await new Promise(resolve => setTimeout(resolve, 800)) console.log('Async Task 2 done') return 'Data from task 2' } asyncTaskQueue.add(asyncTask1) asyncTaskQueue.add(asyncTask2) asyncTaskQueue.run().then(results => console.log('Async queue results:', results)) ``` -------------------------------- ### AsyncQueuer Example Usage Source: https://tanstack.com/pacer/latest/docs/reference/classes/AsyncQueuer.md Demonstrates how to create and use an AsyncQueuer instance. ```APIDOC ## Example Usage ```ts const asyncQueuer = new AsyncQueuer(async (item) => { // process item return item.toUpperCase(); }, { concurrency: 2, onSuccess: (result) => { console.log(result); } }); asyncQueuer.addItem('hello'); asyncQueuer.start(); ``` ```
    Execution Count: {executionCount}
    Rejection Count: {rejectionCount}
    Remaining in Window: {rateLimiter.getRemainingInWindow()}
    Ms Until Next Window: {rateLimiter.getMsUntilNextWindow()}