DEV Community

Cover image for πŸ”₯ use-custom-event-listener, A Lightweight React Hook for Custom Events
 Precious Kelvin Nwaogu
Precious Kelvin Nwaogu

Posted on

πŸ”₯ use-custom-event-listener, A Lightweight React Hook for Custom Events

Ever wished handling custom DOM events in React could be easier? Now it is!

use-custom-event-listener is a zero-dependency, TypeScript-ready React hook that gives you full control over custom events in your app β€” with automatic cleanup, async support, and a slick API.

Created by @marvelcodes πŸ‘


🌟 Features

  • 🎯 TypeScript support out of the box
  • πŸ”„ Listen to one or multiple events with ease
  • 🧹 Auto cleanup when your component unmounts
  • ⚑️ Supports async callbacks
  • 🎨 Simple and expressive API
  • πŸ“¦ Zero dependencies

πŸ“¦ Installation

pnpm add use-custom-event-listener
Enter fullscreen mode Exit fullscreen mode

You can also use npm or yarn.


πŸš€ Usage

Basic Example

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

function MyComponent() {
  useCustomEventListener('dataRefresh', () => {
    console.log('Data refresh event received!');
  });

  return (
    <button onClick={() => dispatchCustomEvent('dataRefresh')}>
      Refresh Data
    </button>
  );
}

Enter fullscreen mode Exit fullscreen mode

Multiple Events

useCustomEventListener(['dataRefresh', 'userUpdate'], () => {
  console.log('Custom event received!');
});

Enter fullscreen mode Exit fullscreen mode

Async Callback Support

useCustomEventListener('dataRefresh', async () => {
  await fetchData();
  await updateUI();
});
Enter fullscreen mode Exit fullscreen mode

πŸ“˜ API Reference

useCustomEventListener

A React hook for listening to one or more custom events.

useCustomEventListener(
  eventNames: string | string[],
  callback: () => Promise<void> | void
)
Enter fullscreen mode Exit fullscreen mode
  • eventNames: A single event name or array of names.
  • callback: Function to run when the event fires (can be async).

dispatchCustomEvent
Dispatches a custom DOM event.

dispatchCustomEvent(eventNames: string | string[])
Enter fullscreen mode Exit fullscreen mode

🧠 Best Practices

  • βœ… Use unique, descriptive event names
  • βœ… Let the hook handle cleanup, no manual work needed
  • βœ… Prefer multiple event names in one hook to reduce overhead
  • βœ… Lean into TypeScript for the best DX

🀝 Contributing

Pull requests welcome!
Check it out on GitHub β†’ github.com/MarvelNwachukwu/use-custom-event-listener


πŸ“œ License

MIT Β© Marvellous Nwachukwu


If you’re building complex React apps that rely on event-driven logic, give this hook a try. It’s intuitive, type-safe, and refreshingly lightweight. Big props to @marvelcodes for this solid addition to the React dev toolkit. πŸ™Œ

Happy coding! πŸš€

Top comments (1)

Collapse
 
aquascript-team profile image
AquaScript Team • Edited

Thanks To Share πŸ‘