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
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>
);
}
Multiple Events
useCustomEventListener(['dataRefresh', 'userUpdate'], () => {
console.log('Custom event received!');
});
Async Callback Support
useCustomEventListener('dataRefresh', async () => {
await fetchData();
await updateUI();
});
π API Reference
useCustomEventListener
A React hook for listening to one or more custom events.
useCustomEventListener(
eventNames: string | string[],
callback: () => Promise<void> | void
)
-
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[])
π§ 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)
Thanks To Share π