use-queue
Usage
Use this hook when you need to limit amount of data in current state and place the rest of it in queue. For example, in @mantine/notifications package amount of notifications that is currently displayed is limited and other new notifications are added to queue and displayed once available space appears.
import { useQueue } from '@mantine/hooks';const { state, queue, add, update, cleanQueue } = useQueue({initialValues: [1],limit: 3,});// state -> [1], queue -> []// When state.length is less that limit, new items are added to stateadd(2);// state -> [1,2], queue -> []// When state.length is equal to limit, new items are added to queueadd(3, 4, 5, 6);// state -> [1,2], queue -> [3,4,5,6]// Use update function to modify itemsupdate((values) => values.map((item) => item * 3));// state -> [3,6], queue -> [9,12,15,18]// If you add or remove items in update function,// they will be divided between queue and state according to limit// order is always preservedupdate((values) => values.filter((item) => item % 2));// state -> [3,9], queue -> [15]// Remove all items from queuecleanQueue();// state -> [3,9], queue -> []// Remove all items from queue and stateupdate(() => []);// state -> [], queue -> []
API
Hook accepts single argument – configuration object with keys:
initialValues
– optional initial values (divided between state and queue according to limit), defaults to empty arraylimit
– maximum amount of items that state can include, every next item after limit is exceeded is put in queue
Return value:
state
– current statequeue
– current queueadd
– add any amount of items to state or queueupdate
– apply given function to all items in state and queue, use it to filter, modify or add itemscleanQueue
– remove all items from queue
Example
Example of use-queue hook usage in Mantine notifications system. By default only 5 notifications can be displayed at a time, rest are added to queue.
TypeScript
By default hook will get types information from initialValues automatically:
const q = useQueue({limit: 2,initialValues: [{ name: 'Bob', id: 1 },{ name: 'Alice', id: 2 },],});typeof q.state[number]; // -> { name: string; id: number; }
If you do not provide initialValues, pass in type for state item:
const q = useQueue<{ name: string; id: number }>({limit: 2,initialValues: [],});q.add({ name: 'Bob', id: 1 });
TypeScript
Definition
function useQueue<T>(configuration: { initialValues?: T[]; limit: number }): {state: T[];queue: T[];add: (...items: T[]) => void;update: (fn: (state: T[]) => T[]) => void;cleanQueue: () => void;};
Item type
Item type is set automatically based on initialValues
,
if you do not have initialValue
it is required to pass in item type:
// ok -> typeof state[number] -> stringconst { state } = useQueue({ initialValues: ['1', '2', '3'], limit: 3 });// type cannot be assigned automatically, specify itconst { state } = useQueue<string>({ limit: 3 });