Skip to content

useQueue

Manage a queue of items

The useQueue hook is helpful when you want to manage a queue of items (based on queue data structure).

It provide with helper methods like add, clear, remove, set, reset and additional properties like firstItem, lastItem and size.

useQueue

First Item
Last Item
Single Item
0
Size: 1Try adding and removing items on the queue.

Usage

Import the hook from @abhushanaj/react-hooks and use in required component.

./src/App.tsx
import React from 'react';
import { useQueue } from '@abhushanaj/react-hooks';
function App() {
const [queue, queueControls] = useQueue([]);
const { remove, add, clear, firstItem, lastItem, size, set, reset } = queueControls;
return (
<div>
<p>Size: {size}</p>
<p>First Item: {firstItem}</p>
<p>Last Item: {lastItem}</p>
<button onClick={clear}>Clear</button>
<button onClick={() => add(queue.length)}>Add Item</button>
<button
onClick={() => {
const removedItem = remove();
console.log(removedItem);
}}
>
Remove Item
</button>
</div>
);
}
export default App;

API Reference

Parameters

ParameterTypeDescriptionDefault
initialQueueArray<T> (optional)The initial queue with items prefilled.[]

Return Value

ParameterTypeDescriptionDefault
queueArray<T>The current queue.N/A
queueControlsQueueControlsThe control options for the queue to add, remove etc.N/A

Types Reference

1. QueueControls

ParameterTypeDescriptionDefault
firstItemT|undefinedThe first item inserted into queue.N/A
lastItemT|undefinedThe last item inserted into queue.N/A
sizenumberThe size of the queue.N/A
clear()=>voidClears the queue to an empty state.N/A
add(newItem: T)=>voidAdds a new item to the queue.N/A
remove()=>T|undefinedRemoves the first inserted (FIFO) and returns the item.N/A
set(newQueue: Array<T>)=>voidSet the current queue state to new queue passed.N/A
reset()=>voidResets the current queue state to the initial queue state.N/A