Salesforce LWC inheritance and code sharing

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.

  1. One complex LWC component that has been broken up into smaller units by composition. Each child control may share exactly the same javascript functions, variables and CSS styling.
  2. A collection of child LWC components that work differently but all raise exactly the same notification event.
  3. 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:

Further Reading:

  1. Composition: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/create_components_compose_intro
  2. Share Javascript code: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.js_share_code
  3. Additional Javascript Files for Sharing Code: https://developer.salesforce.com/docs/component-library/documentation/en/lwc/lwc.create_components_javascript_share
  4. Inheritance in LWC (article by Dhanik Lal Sahni): https://salesforcecodex.com/salesforce/inheritance-in-lightning-web-component/

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s