๐Ÿ“จ 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 (opens in a new tab) pattern is a way to do this. Here are some Pub/Sub libraries:

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 (opens in a new tab) by Hassan Khan-Shaikley (opens in a new tab):

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)), [])