VayuUI

useQueue

A hook to manage a queue state with utility functions.

The useQueue hook provides a simple interface for managing a queue (First-In-First-Out) data structure. It includes methods to add, remove, and clear items, as well as properties to access the first and last elements and the current size.

Demo

First:-
Last:-
Size:0

Queue:

Queue is empty

Source Code

Copy this code into src/hooks/useQueue.ts:

import { useState } from 'react';

export const useQueue = <T,>() => {
  const [queue, setQueue] = useState<T[]>([]);

  const add = (item: T) => {
    setQueue((prevQueue) => [...prevQueue, item]);
  };

  const remove = () => {
    setQueue((prevQueue) => prevQueue.slice(1));
  };

  const clear = () => {
    setQueue([]);
  };

  return {
    queue,
    first: queue.length > 0 ? queue[0] : undefined,
    last: queue.length > 0 ? queue[queue.length - 1] : undefined,
    size: queue.length,
    add,
    remove,
    clear,
  };
};

Usage

import { useQueue } from '@/hooks/useQueue';

const TaskProcessor = () => {
  const { add, remove, first, size, queue } = useQueue<string>();

  return (
    <div>
      <div className="flex gap-2">
        <button onClick={() => add('Task A')}>Add Task A</button>
        <button onClick={() => add('Task B')}>Add Task B</button>
        <button onClick={remove} disabled={size === 0}>
          Process Next Task
        </button>
      </div>

      <p>Current Task: {first}</p>
      <p>Tasks in Queue: {size}</p>

      <ul>
        {queue.map((task, i) => (
          <li key={i}>{task}</li>
        ))}
      </ul>
    </div>
  );
};

API Reference

Return Value

PropertyTypeDescription
queueT[]The array of items currently in the queue.
add(item: T) => voidAdds an item to the end of the queue.
remove() => voidRemoves the first item from the queue.
clear() => voidRemoves all items from the queue.
firstT | undefinedThe first item in the queue.
lastT | undefinedThe last item in the queue.
sizenumberThe number of items in the queue.

On this page