
Take full control of your Next.js application’s execution timing by integrating TanStack Pacer—a lightweight, type-safe utility library for debouncing, throttling, rate-limiting, queuing, and batching. This guide walks through installation, real-world examples, and best practices for each utility, empowering you to optimize API calls, UI updates, and async workflows in your Next.js projects.
1. Installation and Setup
Install the React adapter of TanStack Pacer in your Next.js app:
npm install @tanstack/react-pacer
This single package provides both the core primitives and React-specific hooks—no separate core install required.
2. Debouncing in a Next.js Search Component
Debouncing delays function execution until a specified period of inactivity, ideal for search inputs to avoid firing an API call on every keystroke.
"use client"
import { useState } from "react"
import { useDebouncedValue } from "@tanstack/react-pacer"
import { useRouter, useSearchParams } from "next/navigation"
export default function SearchBar() {
const router = useRouter()
const searchParams = useSearchParams()
const [query, setQuery] = useState(searchParams.get("q") || "")
// Debounce query updates by 300ms
const [debouncedQuery] = useDebouncedValue(query, { wait: 300 })
// Sync debounced value to URL
React.useEffect(() => {
const params = new URLSearchParams(searchParams)
if (debouncedQuery) params.set("q", debouncedQuery)
else params.delete("q")
router.replace(`/?${params.toString()}`)
}, [debouncedQuery, router, searchParams])
return (
<input
type="text"
placeholder="Search..."
value={query}
onChange={e => setQuery(e.target.value)}
/>
)
}
This component updates the URL only after 300 ms of inactivity, dramatically reducing redundant fetches.
3. Throttling Scroll Events
Throttling ensures a function is called at most once per interval. For example, updating a “back to top” button visibility on scroll:
"use client"
import { useState, useEffect } from "react"
import { throttle } from "@tanstack/react-pacer"
export default function ScrollIndicator() {
const [visible, setVisible] = useState(false)
// Throttle scroll handler to once every 200ms
const handleScroll = throttle(() => {
setVisible(window.scrollY > 300)
}, { wait: 200 })
useEffect(() => {
window.addEventListener("scroll", handleScroll)
return () => window.removeEventListener("scroll", handleScroll)
}, [handleScroll])
return visible ? : null
}
This prevents excessive state updates and re-renders during rapid scrolling.
4. Rate Limiting API Calls
Rate limiting caps the number of executions per time window, useful when you must avoid exceeding API rate limits:
import { rateLimit } from "@tanstack/react-pacer"
const limitedFetch = rateLimit(
async (url: string) => {
const res = await fetch(url)
return res.json()
},
{ limit: 5, interval: 60_000 } // max 5 calls per minute
)
// Usage
limitedFetch("/api/data").then(console.log)
Excess calls beyond the limit are dropped until the window resets.
5. Queuing Async Tasks
When every operation must run in order—e.g., sequentially processing form submissions—use queuing:
import { queue } from "@tanstack/react-pacer"
const processQueue = queue(
async id => {
await fetch(`/api/process/${id}`, { method: 'POST' })
},
{ concurrency: 1 } // one at a time
)
processQueue(1)
processQueue(2)
processQueue(3)
All calls are guaranteed to execute in sequence, preventing data loss.
6. Batching Multiple Operations
Batching groups multiple inputs and processes them together to reduce overhead:
import { batch } from "@tanstack/react-pacer"
const processBatch = batch(
items => {
console.log("Batch:", items)
fetch("/api/batch", { method: "POST", body: JSON.stringify(items) })
},
{ maxSize: 5, wait: 2000 }
)
// Add items to be batched
processBatch("A")
processBatch("B")
processBatch("C") // triggers batch when size or time threshold met
Combining items into a single request optimizes network usage and server load.
Conclusion
Integrating TanStack Pacer into your Next.js projects unlocks precise control over function execution, leading to smoother UX, reduced API costs, and improved performance. Whether you’re handling user input, managing API calls, or orchestrating complex async workflows, these utilities are your one-stop shop for execution timing. Give your application the performance edge it deserves—start pacing your code today.