UNPKG

rooks

Version:

Essential React custom hooks ⚓ to super charge your components!

48 lines (47 loc) 1.57 kB
var __spreadArray = (this && this.__spreadArray) || function (to, from, pack) { if (pack || arguments.length === 2) for (var i = 0, l = from.length, ar; i < l; i++) { if (ar || !(i in from)) { if (!ar) ar = Array.prototype.slice.call(from, 0, i); ar[i] = from[i]; } } return to.concat(ar || Array.prototype.slice.call(from)); }; import { useCallback, useState } from "react"; /** * useQueueState * Manages a queue with react hooks. * @param initialList Initial value of the list * @returns The list and controls to modify the queue * @see https://react-hooks.org/docs/useQueueState */ function useQueueState(initialList) { var _a = useState(__spreadArray([], initialList, true)), list = _a[0], setList = _a[1]; var enqueue = useCallback(function (item) { var newList = __spreadArray(__spreadArray([], list, true), [item], false); setList(newList); return newList.length; }, [list]); var dequeue = useCallback(function () { if (list.length > 0) { var firstItem = list[0]; setList(__spreadArray([], list.slice(1), true)); return firstItem; } return undefined; }, [list]); var peek = useCallback(function () { if (list.length > 0) { return list[0]; } return undefined; }, [list]); var controls = { dequeue: dequeue, enqueue: enqueue, length: list.length, peek: peek, }; return [list, controls]; } export { useQueueState };