Queue logic executions among React components

This is just me hacking for fun. So, I was entertaining the idea of improving the performance of hn.tenativeknowledge.com by lazy loading the links when the page load. The current implementation is sort of doing that already. However, I was wondering if I could focus the computing resource on processing and rendering of top links first. Users would likely interact with links at the top before other links down the page. Not sure if that makes much difference in terms of UX for this page, but could be useful in some scenarios. Or not.

Anyhow, it’s an interesting implementation. It would require independent components to coordinate their loading. Coordination among bunch of components is usually done in a common ancestor node. But I just hate adding more wrappers to the component tree. So I decide to implement a hook to do the coordination.

The design is simple. The hook would take 2 parameters:

  • a queue name: so that components can take part in more than one “coordinations”
  • priority: a number that represents the component’s priority in the queue.

Implementation is also simple. Since we’re dealing with priority, so I just get a random Priority Queue implementation off npm. I chose this fastpriorityqueue, because .. its name sounds fast 😆.

The first component that is put in the queue starts right away. I made this decision because it is how I work on my TODO list. If there’s nothing todo, I pick the only task in there. If there are more than one items, then I start sorting them by priority.

Each component is basically associated with a promise. When its promise is resolved, it’s the next in line to execute its logic. When it’s done, it calls a done() function.

done() function implements the logic to schedule the next component. What done() does is it first pops the current component from the priority queue, then resolves the next component in the queue.

Here’s the code: https://github.com/tuan/usePriorityQueue/blob/main/src/hooks/queueHook.ts

Here’s screencast of a fun test app that reads the word from the writting on Statue Of Liberty.

Give me your tired, your poor!

In this app, I just have list of components. Each component displays one word with random delay. The loading priority is the same as the index of the word in the poem.