Docs
useQueue

Add, remove, and clear element from a queue data structure with useQueue.

Installation

pnpm dlx shadcn@latest add https://usekit.kiron.dev/k/use-queue

Usage

"use client"
 
import { useQueue } from "@/hooks/use-queue"
 
interface QueueDemoProps<T> {
  first: T | undefined
  last: T | undefined
  size: number
  queue: T[]
}
 
function QueueDemo<T>({ first, last, size, queue }: QueueDemoProps<T>) {
  return (
    <figure>
      <article>
        <p>Front</p>
        <ul>
          {queue.map((item, i) => {
            const isFirst = first === item
            const isLast = last === item
            return (
              <li key={i}>
                {isFirst && "First: "}
                {isLast && "Last: "}
                {!isFirst && !isLast && "Item: "}
                {String(item)}
              </li>
            )
          })}
        </ul>
        <p>Back</p>
      </article>
      <figcaption>{size} items in the queue</figcaption>
    </figure>
  )
}
 
export function Component() {
  const { add, remove, clear, first, last, size, queue } = useQueue<number>([
    1, 2, 3,
  ])
 
  return (
    <div>
      <header>
        <h1>UseQueue</h1>
        <button onClick={() => add((last || 0) + 1)}>Add</button>
        <button disabled={size === 0} onClick={remove}>
          Remove
        </button>
        <button disabled={size === 0} onClick={clear}>
          Clear
        </button>
      </header>
      <QueueDemo queue={queue} size={size} first={first} last={last} />
    </div>
  )
}

API Reference

Parameters

NameTypeDescriptionDefault ValueOptional
initialValueT[]The initial value for the queue. Defaults to an empty array ([]).[]Yes

Return Values

NameTypeDescription
add(element: T) => voidAdds an element to the end of the queue.
remove() => T | undefinedRemoves and returns the first element from the queue. If the queue is empty, returns undefined.
clear() => voidClears the queue, removing all elements.
firstT | undefinedThe first element in the queue. If the queue is empty, returns undefined.
lastT | undefinedThe last element in the queue. If the queue is empty, returns undefined.
sizenumberThe number of elements in the queue.
queueT[]The current array representing the queue.