useQueueLoading saved progress…

useQueue

A queue is the "first in, first out" line: things join the back and leave from the front, in order. UIs are full of them — a stack of toast notifications shown one at a time, a buffer of analytics events waiting to flush, tasks processed in arrival order. useQueue wraps that structure in React state so the component re-renders as items come and go, with add/remove/clear plus first/last/size accessors.

Implement useQueue(initialValue = []). Return { queue, add, remove, clear, first, last, size }. remove() drops the front item (FIFO) and returns it; the accessors are derived from the current array.

Signature

function useQueue(initialValue = []) {
  // returns { queue, add, remove, clear, first, last, size }
}

Examples

const { add, remove, first, size } = useQueue();
add('toast-1');
add('toast-2');
remove();      // returns 'toast-1' (the oldest), queue is ['toast-2']
first;         // 'toast-2'
const q = useQueue([1, 2, 3]);
q.remove();    // 1
q.last;        // 3
q.size;        // 2

Notes

  • FIFOadd appends to the back; remove takes from the front. First in, first out.
  • remove returns the item — hand back the dropped front element (or undefined when empty) so callers can process it.
  • Immutable updates — build a new array ([...q, item], q.slice(1)); never mutate state or the caller's initial array in place.
  • Stable controlsadd/remove/clear keep one identity across renders; first/last/size are recomputed from the current queue.
Loading editor…