
Use Priority Queue is a React hook that provides a simple and efficient way to manage a priority queue in your React applications. It uses a binary heap under the hood, with values stored inside a JavaScript array.
O(log n), space: O(1)O(log n), space: O(1)O(1), space: O(1)O(1), space: O(1)Install the package as a dependency on your project by running:
An interactive example can be found on CodeSandbox.
By default usePriorityQueue() uses a min binary heap (lower priority numbers are prioritized first) to determine the priority of its nodes. The usePriorityQueue() hook can accept a custom comparator of the following signature:
comparator(a, b) return value:
b as a higher priority than a, e.g. [b, a]a as a higher priority than b, e.g. [a, b]a and b are equal priorityBy default, the comparator is set to minHeapComparator():
You are welcome to supply your custom comparator to the usePriorityQueue() hook. A custom comparator can completely ignore a.priority and b.priority and use a.value and b.value instead. For example, if you want to sort blog posts by timestamp, you can do the following:
The usePriorityQueue() hook is a wrapper around the PriorityQueue class. You can use the PriorityQueue class directly to manage the queue outside a React component. The PriorityQueue class has the same API as the usePriorityQueue() hook, but it does not have the React-specific features like reactivity every time a node is added or removed.
Use Priority Queue is distributed under MIT license, Copyright (c) 2025 Andrew Vo-Nguyen. See LICENSE for more information.