Github Project: https://github.com/andrewwhitten/Salesforce-LWC-Snippets
Salesforce Lightning Web Components (LWC) were only introduced recently in the Spring ’19 release in 2019, and have rapidly taken over from Aura as the default choice to create new User Interface components.
The ease of use and deployment is impressive, although every time you create a customization for your Salesforce org, whether it be an Apex trigger class, custom object or LWC component, you are also creating an artefact that will require maintenance for a long time.
Salesforce provide guidance on LWC composition, which is to say the best way to build components is to build them out of smaller components like Lego. They even say “Inheritance is allowed, but it isn’t recommended because composition is usually more effective“. This is good advice on the smaller side of things; if your org has a maximum of 30 LWC controls then over-engineering your LWC components isn’t going to be productive.
I can however think of scenarios where it is worth considering from an architectural point of view.
- A collection of child LWC components that work differently but all raise exactly the same notification event.
- A suite of 10 functionally independent LWC components that should share specific styling. A style change in one should reflect in the others.
I have created a purposefully simple project on GitHub that demonstrates how you can use inheritance for simplifying your child LWC components. The code is simple enough that you can see how the inheritance works and change it real time in your local development server:
- Composition: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_components_compose_intro
- Inheritance in LWC (article by Dhanik Lal Sahni): https://salesforcecodex.com/salesforce/inheritance-in-lightning-web-component/