@supunlakmal/hooks
Version:
A collection of reusable React hooks
49 lines • 1.84 kB
JavaScript
import { useState, useCallback, useMemo } from 'react';
/**
* Manages a stateful queue (First-In, First-Out).
* Provides methods to add, remove, peek, and clear the queue, along with its current state.
*
* @template T The type of items the queue will hold.
* @param initialQueue An optional initial array of items to populate the queue.
* @returns An object containing the queue state and methods to interact with it.
*/
export function useQueue(initialQueue = []) {
const [queue, setQueue] = useState(initialQueue);
/** Adds an item to the end of the queue. */
const add = useCallback((item) => {
setQueue((prevQueue) => [...prevQueue, item]);
}, []);
/** Removes the item from the front of the queue. */
const remove = useCallback(() => {
setQueue((prevQueue) => {
if (prevQueue.length === 0) {
return [];
}
return prevQueue.slice(1); // Return new array excluding the first item
});
}, []);
/** Returns the item at the front of the queue without removing it. */
const peek = useCallback(() => {
return queue[0];
}, [queue]); // Depends on the current queue state
/** Removes all items from the queue. */
const clear = useCallback(() => {
setQueue([]);
}, []);
// Memoize derived values to avoid recalculating on every render
const size = useMemo(() => queue.length, [queue]);
const first = useMemo(() => queue[0], [queue]);
const last = useMemo(() => queue[queue.length - 1], [queue]);
// Return the state and the memoized methods
return {
add,
remove, // Use the corrected version
peek,
size,
first,
last,
queue, // Provide read-only access
clear,
};
}
//# sourceMappingURL=useQueue.js.map