ryardley / ts-bus

A lightweight JavaScript/TypeScript event bus to help manage your application architecture.
MIT License
135 stars 8 forks source link

Discussion: Handle subscription (React) #19

Closed dmicic closed 5 years ago

dmicic commented 5 years ago

Some random thoughts which went through my mind in regards to the subscription management.

And should the useEffect() also cleanup the subscription when the component B unmounts? (goes back to the first bullet point)
This here would be my preferred solution. Would be good to have a hook for that to avoid boilerplate code.
```ts
useEffect(() => {
  bus.subscribe("componentA.event", handler)

  return function cleanup() {
      bus.unsubscribe("componentA.event", handler)
    };

}, [bus]);
dmicic commented 5 years ago

Ah, I saw now that the subscribe method returns a function which can be used to unsubscribe.

https://github.com/ryardley/ts-bus/blob/4fd905f0e17ea52803586620c462f342592d9666/src/EventBus.ts#L68

ryardley commented 5 years ago

That is correct mind I close this? I am pretty sure the docs mention it but possibly don't cover it in detail.