Use Custom Event Listener

by Marvellous Nwachukwu

A tiny React hook for cross-component custom DOM events. I built it for IQAICOM/iq-agents, the agent trading platform at app.iqai.com, then extracted it into its own npm package.

The problem

User clicks BUY. The trade goes through. Now five different parts of the UI need to know: the portfolio panel refetches positions, the trade history re-renders, the wallet balance updates, the cache layer busts a few keys, the notifications system fires a confirmation toast. Some of these components have no direct relationship in the tree. Prop drilling is painful, Context re-renders everyone, and React Query invalidation alone doesn't cover the non-data side effects.

What I wanted: an after-trade signal any component could subscribe to, with no shared parent and no global store wiring.


The hook

That's all it is. A useEffect that wires document event listeners to a
callback, with cleanup on unmount. The dispatcher posts a CustomEvent to document. Under 50 lines of source.

import {
  useCustomEventListener,
  dispatchCustomEvent,
} from 'use-custom-event-listener';

// Anywhere that needs to react to trades
useCustomEventListener('trade:settled', async () => {
  await queryClient.invalidateQueries(['positions']);
  await queryClient.invalidateQueries(['balance']);
  toast.success('Trade settled');
});

// In the trade handler
dispatchCustomEvent('trade:settled');


Subscribing to multiple events

Same hook accepts an array. The callback fires for any of them.

useCustomEventListener(['trade:settled', 'wallet:reconnected'], refreshAll);


Why not just use ...


Why a package

It started as a single file in iq-agents. Once it stabilised, extracting
it to a package was the obvious next step. Next project gets it for free.

Install

pnpm add use-custom-event-listener


Stack

TypeScript, compiled with tsc. Zero runtime dependencies. React 17/18 peer dep. MIT.

Source: https://github.com/MarvelNwachukwu/use-custom-event-listener
npm: https://www.npmjs.com/package/use-custom-event-listener
Where it's used: https://app.iqai.comhttps://www.tupredices.com/en

#WebBlog