Skip to content
Latestv1.0.63

useQueue

useQueue is a general-purpose task queue management Hook for controlling request concurrency, sequencing tasks, failure retries, and more. It is especially suitable for enterprise scenarios like batch export, bulk operations, and file uploads.

Basic Concurrency Control

Run 6 tasks with a concurrency limit of 2. The queue demo shows real-time state transitions.

Task Queue Concurrency Demo

Options

OptionTypeDefaultDescription
concurrencynumber1Max number of tasks running simultaneously
autoStartbooleantrueWhether to auto-start after adding a task
continueOnErrorbooleanfalseWhether to continue the queue when a task fails
onTaskComplete(task) => void-Callback when a single task completes
onTaskError(task, error) => void-Callback when a single task fails
onAllComplete(tasks) => void-Callback when all tasks in the queue are finished

Priority Sorting & Failure Retry

High-priority tasks execute first. Failed tasks can be retried individually or all at once.

Priority & Retry Demo

Task Structure

typescript
interface QueueTask<T = unknown> {
  id: string
  key?: string // Deduplication key
  task: (options: { signal: AbortSignal }) => Promise<T>
  priority?: number // Higher = runs first
  status: 'pending' | 'running' | 'fulfilled' | 'rejected' | 'canceled'
  result?: T
  error?: Error
  metadata?: Record<string, unknown>
  createdAt: number
  startTime?: number
  endTime?: number
  delay?: number // Delay before execution (ms)
}

Adding Tasks

typescript
const taskId = add(
  async ({ signal }) => {
    const res = await request.get('/api/report/1', { signal })
    return res.data
  },
  {
    key: 'report-1', // Used for deduplication / cancellation
    priority: 10, // Higher number = higher priority
    delay: 1000, // Wait 1s before starting
    metadata: { type: 'report' }
  }
)

start()

Concurrency Control

typescript
const { add, start, pause, resume, isRunning } = useQueue({
  concurrency: 5, // Max 5 tasks simultaneously
  autoStart: true
})

for (let i = 0; i < 100; i++) {
  add(() => request.get(`/api/item/${i}`).then((res) => res.data))
}

Error & Retry

typescript
const { failedTasks, retry, retryAll } = useQueue({
  concurrency: 2,
  continueOnError: true,
  onTaskError: (task, error) => {
    console.error('Task failed:', task.id, error)
  },
  onAllComplete: (tasks) => {
    console.log('All tasks done:', tasks.length)
  }
})

retry(taskId) // Retry a single task
retryAll() // Retry all failed tasks

API Reference

Method / StateDescription
add(task, options)Add a task, returns task ID
remove(taskId)Remove a task
clear()Clear the entire queue
start()Start processing the queue
pause() / resume()Pause / resume processing
cancel(taskId) / cancelAll()Cancel task(s)
retry(taskId) / retryAll()Retry failed task(s)
getTask(taskId)Get a task by ID
pendingTasks / runningTasks / completedTasks / failedTasksTask lists by state
isRunning / isEmpty / isAllCompleteOverall queue state
completedCount / totalCountCompletion / total count

Advanced: useRequestQueue

The library also provides useRequestQueue, which wraps useQueue with HTTP-request-level conveniences (built-in addRequest() and cancelByKey()). See the useRequestQueue page for more.

Released under the MIT License.