I have a very simple hook that works as intended:
const subscriptions: Subscription[] = []
const useEvents = () => {
const subscribe = (type: Type, callback: () => void) => {
const id = nanoid(8)
subscriptions.push({
id,
type,
callback,
})
return () => {
subscriptions.splice(
subscriptions.findIndex((s) => s.id === id),
1
)
}
}
const dispatch = (type: Type) => {
for (const subscription of subscriptions.filter((s) => s.type === type)) {
subscription.callback()
}
}
return { subscribe, dispatch }
}
I subscribe so:
useEffect(() => {
subscribe("run", () => {
console.log("RUN!!")
})
}, [])
The problem is that when the app is hot-reloading subscribe is called again and the callback duplicated, is there any way to avoid this?