BasicUtils

TanStack Pacer Tutorial

Published: May 1, 2025

By: Joseph Horace

#TanStack Pacer
#TanStack Pacer tutorial
#React debounce hook
#React throttle hook
#async queue React
#rate limiting React
#TanStack Pacer example
#useDebouncedCallback
#useThrottler
#useRateLimitedCallback

Table of Contents

  1. Introduction
  2. What is TanStack Pacer?
  3. Installation
  4. Core Concepts
  5. Tanstack Pacer Debouncing Code Example (React + TypeScript)
  6. Tanstack Pacer Throttling Coding Example (React + TypeScript)
  7. Tanstack Pacer Rate Limiting Coding Example (React + TypeScript)
  8. Tanstack Pacer Queue Coding Example
  9. Tanstack Pacer Async Queueing Coding Example (React + TypeScript)
  10. Tanstack Pacer vs P-Limit vs Bottleneck vs Lodash (Debounce/Throttle) vs RxJS vs Native setTimeout/setInterval
  11. Conclusion

Introduction

In modern web development, especially with React, we often juggle multiple async operations which can easily lead to performance bottlenecks, race conditions, or exceeding rate limits.

TanStack Pacer is a framework-agnostic library that gives the user a set of utilities for controlling execution timing. Whether you want to debounce, throttle, rate-limit API calls, or even manage queues of async tasks, Pacer is the right tool for you.

In this tutorial, we will discuss how to use Pacer for:

  • Debouncing and throttling
  • Rate-limiting backend requests
  • Queuing async tasks for predictable execution order
  • Integrating TanStack Pacer with React using built-in hooks

Let’s dive in.

What is TanStack Pacer?

TanStack Pacer is a solution for controlling async function execution. Here is a definition of its most important functionalities:

  • Debouncing: Delaying execution until the user has stopped interacting for a set period.
  • Throttling: Limiting the rate at which a function is called.
  • Rate-limiting: Controlling the number of requests sent to an API to avoid exceeding limits.
  • Queuing: Managing the order of async tasks.

Installation

You can install TanStack Pacer via NPM.

Here’s how you would do it in different environments:

React

npm install @tanstack/react-pacer

Solid

npm install @tanstack/solid-pacer

Vanilla JS

npm install @tanstack/pacer

Core Concepts

Before diving into the fun part—code examples—let’s first understand the core concepts of TanStack Pacer and their applications.

1. Debouncing

Debouncing refers to delaying the execution of a function until a specified period of inactivity is sensed. It's important to avoid making too many function calls when we can combine them into a single, efficient call.

Example Use Case: Debouncing a search input to avoid excessive API calls.

2. Throttling

Throttling refers to limiting the number of times a function can fire over a given period.

Example Use Case: Throttling a scroll event handler to avoid executing it too frequently, which could negatively impact performance.

3. Rate Limiting

Rate limiting controls the number of times a function can be called over time. It’s essential to avoid server overload and ensure compliance with rate limits.

Example Use Case: Rate-limiting API calls to ensure that requests don't exceed a defined threshold over a specified time period.

4. Queueing

Queueing is essential for maintaining the order in which async tasks are executed. It can take various forms, such as FIFO (first in, first out), LIFO (last in, first out), or priority-based execution.

Example Use Case: Managing a queue of background tasks, like file uploads, to avoid overwhelming the server or negatively affecting client-side performance.

Tanstack Pacer Debouncing Code Example (React + TypeScript)

'use client'
import { useDebouncedCallback } from '@tanstack/react-pacer'
import { useState } from 'react'
export default function DebouncedSearch() {
  const [query, setQuery] = useState('')
  // Debounce the search handler with a 500ms delay
  const handleSearch = useDebouncedCallback((value: string) => {
    console.log('Searching for:', value)
    // Here you'd typically call an API
  }, {
    wait: 500,
  })
  return (
    <input
      type="text"
      placeholder="Search..."
      value={query}
      onChange={(e) => {
        const val = e.target.value
        setQuery(val)
        handleSearch(val)
      }}
    />
  )
}

How It Works

  • The useDebouncedCallback hook returns a function that delays execution until the user stops typing for 500ms.
  • This avoids spamming your API or expensive logic while typing rapidly.
  • Useful for: search fields, live filtering, or any high-frequency input interaction.

Tanstack Pacer Throttling Coding Example (React + TypeScript)

import { useState } from 'react'
import { useThrottler } from '@tanstack/react-pacer'
export default function ThrottlingDemo() {
  const [clicks, setClicks] = useState(0)
  // Throttle the click handler to only allow one click every 1 second (1000ms)
  const throttler = useThrottler(
    () => setClicks((prev) => prev + 1),
    { wait: 1000 }
  )
  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <button onClick={throttler}>Click me (throttled)</button>
      <p>Number of Clicks: {clicks}</p>
    </div>
  )
}

How It Works

  • State: clicks keeps track of the number of button clicks.
  • Throttling: useThrottler is used to throttle the click handler, limiting it to one click every 1000ms (1 second).
  • Button: When clicked, the throttler function is triggered, but clicks are only counted once per second due to throttling.
  • Result: Even if the button is clicked multiple times quickly, the clicks value increases by one per second.

Tanstack Pacer Rate Limiting Coding Example (React + TypeScript)

import { useState } from 'react'
import { useRateLimitedCallback } from '@tanstack/react-pacer'
export default function RateLimitDemo() {
  const [count, setCount] = useState(0)
  // Allow only 5 calls every 10 seconds
  const handleClick = useRateLimitedCallback(
    () => {
      setCount((prev) => prev + 1)
    },
    { limit: 5, window: 10000 } // 5 calls per 10,000ms (10s)
  )
  return (
    <div style={{ padding: 20, fontFamily: 'sans-serif' }}>
      <button onClick={handleClick}>Rate-limited Click</button>
      <p>Allowed Clicks Count: {count}</p>
    </div>
  )
}

How It Works

  • count: Tracks successful button clicks.
  • useRateLimitedCallback: Limits handler execution to 5 times every 10 seconds.
  • Additional clicks beyond 5 within that window are ignored.
  • Counter only increments if the limit hasn’t been exceeded.

Tanstack Pacer Queue Coding Example

import { queue } from '@tanstack/pacer'
// Create a queue that processes items every second
const processItems = queue<number>({
  wait: 1000,
  onItemsChange: (queuer) => {
    console.log('Current queue:', queuer.getAllItems())
  }
})
// Add items to be processed
processItems(1) // Processed immediately
processItems(2) // Processed after 1 second
processItems(3) // Processed after 2 seconds

How It Works

  • The queue processes the items one by one, respecting the wait time of 1000ms (1 second).
  • The onItemsChange callback will log the current state of the queue each time an item is added, showing you the current list of queued items.

Tanstack Pacer Async Queueing Coding Example (React + TypeScript)

import { asyncQueue } from '@tanstack/pacer'
// Create a queue that processes up to 2 items concurrently
const processItems = asyncQueue<string>({
  concurrency: 2,
  onItemsChange: (queuer) => {
    console.log('Active tasks:', queuer.getActiveItems().length)
  }
})
// Add async tasks to be processed
processItems(async () => {
  const result = await fetchData(1)
  return result
})
processItems(async () => {
  const result = await fetchData(2)
  return result
})

How It Works

This code will set up an asynchronous queue that handles up to two tasks at the same time and logs the number of active tasks each time the queue changes.

Tanstack Pacer vs P-Limit vs Bottleneck vs Lodash (Debounce/Throttle) vs RxJS vs Native setTimeout/setInterval

p-limit

p-limit is a lightweight utility for limiting the number of concurrent promises running at once.

Pros: Simple, minimalistic API for concurrency control.

Cons: No support for debouncing, throttling, or queuing tasks.

Use Case: Good if you only need to limit concurrency but don’t need the full suite of async controls.

Bottleneck

Bottleneck is a more feature-rich solution for rate-limiting and queue management.

Pros: More extensive rate-limiting and queuing options.

Cons: Larger bundle size, steeper learning curve.

Use Case: Good if you need highly customizable rate-limiting and queuing features. However, TanStack Pacer offers a simpler, more lightweight approach for common use cases like debouncing and throttling.

Lodash (Debounce/Throttle)

Lodash is a widely-used utility library with many helpful functions, including debounce and throttle.

Pros: Mature library with excellent community support and a lot of features.

Cons: Larger bundle size, no support for async queuing or rate-limiting.

Use Case: Lodash is a great option for general utility functions, but if you need to manage async tasks beyond simple debounce or throttle, TanStack Pacer provides more specialized functionality.

RxJS

RxJS is a powerful reactive programming library that allows you to work with asynchronous events using Observables.

Pros: Extremely powerful for reactive programming and complex event-driven architectures.

Cons: Steep learning curve, potentially overkill for simple tasks, large bundle size.

Use Case: If you’re already working with reactive programming and need advanced async control, RxJS might be a good fit. However, for simpler cases, TanStack Pacer provides a lighter, easier-to-use solution.

Conclusion

In this tutorial, we have covered how TanStack Pacer can streamline the management of async operations in your web applications. Whether you desire to debounce user inputs, throttle events, rate-limit API calls, or queue tasks, TanStack provides powerful and well-tested tools for all of this.

We have covered installation and shown code examples of how to use TanStack Pacer in React. Additionally, we have compared TanStack Pacer with other popular alternatives, highlighting the pros and cons of each to help you make an informed decision. Now that you are familiar with TanStack Pacer, you can start using it in your projects.

Happy coding!

References

Background References

  1. (March 10, 2025). Https://tanstack.com/pacer/latest/docs/overview. *TanStack Pacer*. Retrieved March 10, 2025 from https://tanstack.com/pacer/latest/docs/overview

About the Author

Joseph Horace

Horace is a dedicated software developer with a deep passion for technology and problem-solving. With years of experience in developing robust and scalable applications, Horace specializes in building user-friendly solutions using cutting-edge technologies. His expertise spans across multiple areas of software development, with a focus on delivering high-quality code and seamless user experiences. Horace believes in continuous learning and enjoys sharing insights with the community through contributions and collaborations. When not coding, he enjoys exploring new technologies and staying updated on industry trends.