Skip to content
usefy

useQueue

State & data

A React hook for managing FIFO queue state with immutable updates

Install

$ npm install @usefy/use-queue

Quick start

useQueue.tsx
import { useQueue } from "@usefy/use-queue";

interface Task {
  id: number;
  label: string;
}

function TaskRunner() {
  const [queue, { add, remove, peek }] = useQueue<Task>([]);

  const processNext = () => {
    const task = remove(); // dequeue + get the item in one call
    if (task) runTask(task);
  };

  return (
    <div>
      <button onClick={() => add({ id: Date.now(), label: "New" })}>
        Add task
      </button>
      <button onClick={processNext} disabled={queue.length === 0}>
        Process next {peek()?.label}
      </button>
      <p>Pending: {queue.length}</p>
    </div>
  );
}

API reference

useQueue<T>(initialState?)

Returns a tuple of the current read-only queue and a stable actions object.

Parameters

ParameterTypeDefaultDescription
initialStateQueueInitializer<T>emptyAn array, an iterable of values, or a factory returning one (evaluated once). The first element becomes the front.

Returns [queue, actions]

ItemTypeDescription
queuereadonly T[]Current queue. queue[0] is the front; the last item is the back
actionsUseQueueActions<T>Stable action handlers (see below)

Actions

ActionSignatureDescription
add(...items: T[]) => voidEnqueue one or more items to the back. Calling with no items is a no-op
remove() => T | undefinedDequeue the front item and return it. Returns undefined (no-op) when empty
peek() => T | undefinedRead the front item without mutating (stable, always reflects latest state)
clear() => voidRemove all items. Clearing an empty queue is a no-op
reset() => voidRestore the initial values (a fresh copy)

Reading first / last / size

The returned queue is a read-only array, so these derive directly from it — no extra state needed:

const [queue] = useQueue<number>([1, 2, 3]);

const first = queue[0];                    // 1  (front, next to dequeue)
const last = queue[queue.length - 1];      // 3  (back, most recently added)
const size = queue.length;                 // 3

The returned queue is a readonly T[], so calling queue.push(...) directly is a TypeScript error. Use the actions — mutating the array in place would bypass React state and break re-renders.


Go deeper

This page is the quick reference. For every example, prop, and edge case, read the full README — or open Storybook to change props live.

More in state & data