๐จ Events & Messaging
Depending on the architecture you are using, you might need to communicate between components or between different parts of your codebase. The Pub/Sub pattern is a way to do this. Here are some Pub/Sub libraries:
- StarsNPMTSMaintained
- 2k23M/w
- 10k5M/w
- 5k130k/w3 years
- 9003M/w5 years
- 2305M/w8 years
- 3k20k/w3 years
- 20100/w2 years
Compare on NPMTrends and Star History (requires a GH token)
About these numbers and colors
If you donโt want to use a library, see PubSub in 150 bytes by Hassan Khan-Shaikley:
const eventTarget = new EventTarget()
export const subscribe = (eventName, callback) => {
eventTarget.addEventListener(eventName, callback)
return () => {
eventTarget.removeEventListener(eventName, callback)
}
}
export const publish = (n, data) => {
eventTarget.dispatchEvent(new CustomEvent(n, { detail: data }))
}
And then use it with:
const unsubscribe = subscribe('SOME_EVENT', e => {
console.log(e.detail)
})
publish('SOME_EVENT', { hello: 'world' })
// logs {hello: 'world'}
unsubscribe()
publish('SOME_EVENT', 123)
// does nothing
React
When using React, you can subscribe your components to events using useEffect
. Subscription functions typically return an unsubscribe
function that you can call when the component unmounts:
useEffect(() => {
const unsubscribe = subscribe('SOME_EVENT', e => {
console.log(e.detail)
})
return () => {
unsubscribe()
}
}, [])
Short version:
useEffect(() => subscribe('SOME_EVENT', e => console.log(e.detail)), [])