Last active
April 4, 2024 17:55
-
-
Save l-portet/d77babf5fa102d27ff0985bf31d8b591 to your computer and use it in GitHub Desktop.
utility hook for event communication in React components
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { useEffect, useState } from 'react'; | |
type Callback = (data?: any) => void; | |
class EventBus<E extends string = string> { | |
events: Partial<Record<E, Callback[]>>; | |
constructor() { | |
this.events = {}; | |
} | |
on(event: E, callback: Callback) { | |
if (!this.events[event]) { | |
this.events[event] = []; | |
} | |
this.events[event]!.push(callback); | |
} | |
off(event: E, callback: Callback) { | |
if (!this.events[event]) { | |
return; | |
} | |
this.events[event] = this.events[event]!.filter((fn) => fn !== callback); | |
} | |
clear() { | |
this.events = {}; | |
} | |
emit(event: E, data?: any) { | |
if (!this.events[event]) { | |
return; | |
} | |
this.events[event]!.forEach((callback) => callback(data)); | |
} | |
} | |
export default function useEventBus<E extends string = string>() { | |
const [bus] = useState(new EventBus<E>()); | |
useEffect(() => () => bus.clear(), []); | |
return bus; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment