ahooks
Version:
react hooks library
37 lines (36 loc) • 1.17 kB
JavaScript
import { useRef, useEffect } from 'react';
export class EventEmitter {
constructor() {
this.subscriptions = new Set();
this.emit = (val) => {
for (const subscription of this.subscriptions) {
subscription(val);
}
};
this.useSubscription = (callback) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const callbackRef = useRef(undefined);
callbackRef.current = callback;
// eslint-disable-next-line react-hooks/rules-of-hooks
useEffect(() => {
function subscription(val) {
if (callbackRef.current) {
callbackRef.current(val);
}
}
this.subscriptions.add(subscription);
return () => {
this.subscriptions.delete(subscription);
};
}, []);
};
}
}
const useEventEmitter = () => {
const ref = useRef(undefined);
if (!ref.current) {
ref.current = new EventEmitter();
}
return ref.current;
};
export default useEventEmitter;