Cover image

Use Priority Queue

About

Copy heading link

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.

Copy heading link

Complexity

Copy heading link
  • Enqueue - time: O(log n), space: O(1)
  • Dequeue - time: O(log n), space: O(1)
  • Next (Peek) - time: O(1), space: O(1)
  • Size - time: O(1), space: O(1)

Installation

Copy heading link

Install the package as a dependency on your project by running:

Shell
Shell
Shell

Live demo

Copy heading link

An interactive example can be found on CodeSandbox.

Basic usage

Copy heading link
TypeScript

Comparators

Copy heading link

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:

TypeScript

comparator(a, b) return value:

  • > 0: b as a higher priority than a, e.g. [b, a]
  • < 0: a as a higher priority than b, e.g. [a, b]
  • === 0: a and b are equal priority

By default, the comparator is set to minHeapComparator():

TypeScript

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:

TypeScript

PriorityQueue class

Copy heading link

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.

TypeScript

License

Copy heading link

Use Priority Queue is distributed under MIT license, Copyright (c) 2025 Andrew Vo-Nguyen. See LICENSE for more information.