1
0
mirror of https://github.com/Unleash/unleash.git synced 2025-01-06 00:07:44 +01:00
unleash.unleash/frontend/src/hooks/useCustomEvent.ts
2024-05-29 16:01:52 +02:00

28 lines
784 B
TypeScript

import { useCallback, useEffect } from 'react';
/**
* A hook that provides methods to emit and listen to custom DOM events.
* @param eventName The name of the event to listen for and dispatch.
*/
export const useCustomEvent = (
eventName: string,
handler: (event: CustomEvent) => void,
) => {
const emitEvent = useCallback(() => {
const event = new CustomEvent(eventName);
document.dispatchEvent(event);
}, [eventName]);
useEffect(() => {
const eventListener = (event: Event) => handler(event as CustomEvent);
document.addEventListener(eventName, eventListener);
return () => {
document.removeEventListener(eventName, eventListener);
};
}, [eventName, handler]);
return { emitEvent };
};