function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Roy SouravRoy Sourav 

LWC - pubsub or custom event

LWC - type of communication we should use

Scenario - we have two child components (siblings) inside a container/parent component. Now if the two siblings want to communicate between each other, what's the best possible way -

1. Pubsub
or
2. Child 1 fires a custom event and the parent again passes the required data to child 2 ? If possible , is this a good practice? 

Please let me know the best practices here. Thanks in advance.

 
Best Answer chosen by Roy Sourav
Suraj Tripathi 47Suraj Tripathi 47
Hi Roy Sourav,

You can use the PubSub insted of your second approch.
But also pubsub is old way. You should go with the Lightning Message Service.
Here I give you the best references:-
1. For pub sub :- https://www.sfdcpanther.com/pub-sub-in-lightning-web-component/
2. For Lightning Message Service :- https://www.sfdcpanther.com/lightning-message-services/ :- 

If you face any problem then post it.
Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Suraj Tripathi.

All Answers

AbhishekAbhishek (Salesforce Developers) 
Hi Roy,

Your query is answered here,

https://stackoverflow.com/questions/47425038/own-pubsub-implementation-vs-using-addeventlistener-customevent

https://gist.github.com/cedmax/1000193/f357ec2c9ad96ce7e6f4894f0f17802e42df2ef3

I hope you find the above solution helpful. If it does, please mark as Best Answer to help others too.

Thanks.
Suraj Tripathi 47Suraj Tripathi 47
Hi Roy Sourav,

You can use the PubSub insted of your second approch.
But also pubsub is old way. You should go with the Lightning Message Service.
Here I give you the best references:-
1. For pub sub :- https://www.sfdcpanther.com/pub-sub-in-lightning-web-component/
2. For Lightning Message Service :- https://www.sfdcpanther.com/lightning-message-services/ :- 

If you face any problem then post it.
Please mark it as best answer if it helps you to fix the issue.

Thank you!

Regards,
Suraj Tripathi.
This was selected as the best answer