3

Custom Events are used to pass the data from child component to parent component but we can achieve the same functionality with Lightning Messaging Service(LMS). What is the benefit of using custom event over LMS? or Why we should use custom events to send data from child component to parent component in LWC?

1
  • 8
    LMS is quite heavy weight and intended for cross-hierarchy and cross-technology communications. Custom events are light weight and simple to use in parent/child component scenarios. The communication for events is declarative via handler bindings in the component template, making it easy to understand. You should not use LMS where you can use custom events because it is simply unnecessary, makes your code more complex and exposes your components to additional limitations.
    – Phil W
    Commented Oct 14, 2022 at 11:12

1 Answer 1

9

LMS has only one benefit: it can communicate across components anywhere in the DOM hierarchy.

Now, let's look at the drawbacks:

  • If you forget to unsubscribe, you leak memory, which can cause an app to crash or malfunction.
  • Every subscriber gets every message, which can be resource intensive, causing lag, freezes, and crashes.
  • You can no longer just look in a few places (ideally, just in markup) to determine which events are handled.
  • You have to deploy extra metadata to even use an LMS channel.
  • With multiple instances of a component, you have to coordinate a way for each component to get the right message.
  • You can introduce race conditions as components are loaded/unloaded.
  • It becomes harder to maintain and add new features, since LMS changes the paradigm of how events are registered.
  • It's harder to debug when things go wrong, as you have to set multiple breakpoints and/or step through extra library code to see the connection on both ends.
  • It doesn't work everywhere LWC is supported.
  • It works across namespaces, meaning a clever developer could listen in to your messages that are meant only for your app, or could even inject fake messages, a potential security risk.

Ultimately, overuse of LMS or its' predecessor, pubsub, will make every aspect of the app worse: slower, more prone to crashes, harder to add new features, and so on. Every change requires careful consideration.

You use LMS because it's the least painful way to communicate between, for example, Aura and LWC. You should prefer CustomEvent and data binding as two-way communication between parent and child, pubsub for controlled cross-component communication within your own app, and LMS only if you need some esoteric use case, like communicating with apps in other namespaces, or in components that are arbitrarily apart and event/data binding is more complicated than using LMS.

Not the answer you're looking for? Browse other questions tagged .