useQueue
State & dataA React hook for managing FIFO queue state with immutable updates
Install
$ npm install @usefy/use-queueQuick start
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
| Parameter | Type | Default | Description |
|---|---|---|---|
initialState | QueueInitializer<T> | empty | An array, an iterable of values, or a factory returning one (evaluated once). The first element becomes the front. |
Returns [queue, actions]
| Item | Type | Description |
|---|---|---|
queue | readonly T[] | Current queue. queue[0] is the front; the last item is the back |
actions | UseQueueActions<T> | Stable action handlers (see below) |
Actions
| Action | Signature | Description |
|---|---|---|
add | (...items: T[]) => void | Enqueue one or more items to the back. Calling with no items is a no-op |
remove | () => T | undefined | Dequeue the front item and return it. Returns undefined (no-op) when empty |
peek | () => T | undefined | Read the front item without mutating (stable, always reflects latest state) |
clear | () => void | Remove all items. Clearing an empty queue is a no-op |
reset | () => void | Restore 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
queueis areadonly T[], so callingqueue.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.