Skip to main content

useQueue

The useQueue hook manages a first-in, first-out (FIFO) queue as React state. Items are added to the end and removed from the front, which makes it a good fit for notifications, upload lists, or any job that must be processed in order.

Usage​

Installation​

import { useQueue } from "hookstorm";

Parameters​

  • initialQueue — (optional) Initial items. The first item is the next one to be removed.

Return Values​

  • queue — The current items, oldest first.
  • first — The next item to be removed, or undefined when the queue is empty.
  • last — The most recently added item, or undefined when the queue is empty.
  • size — The number of items.
  • add(...items) — Appends one or more items to the end.
  • remove() — Removes the first item and returns it (undefined when the queue is empty).
  • clear() — Removes all items.

Example Usage​

import { ReactElement } from "react";
import { useQueue } from "hookstorm";

export default function JobRunner(): ReactElement {
const { add, remove, first, size } = useQueue<string>(["resize.png"]);

return (
<div>
<p>
Next job: {first ?? "none"} ({size} waiting)
</p>
<button onClick={() => add(`file-${Date.now()}.png`)}>Enqueue</button>
<button
onClick={() => {
const job = remove();
if (job) console.log("processing", job);
}}
>
Process next
</button>
</div>
);
}

Notes​

  • remove returns the removed item synchronously, and calling it several times in one event handler removes items in order.
  • Action functions have a stable identity, so they are safe to pass to memoized children.