LWC Coding Best Practices

by Rijwan Mohmmed
0 comment
lwc-coding-best-practices-techdicer

Hello friends, today we are going to discuss LWC Coding Best Practices. We can improve LWC component performance by using Best Practices of LWC coding. One of the best practices for building LWC Components is to use modules for reusability. 

Also, check this: Difference between View All, Modify All and View All Data, Modify All Data in Salesforce

Key Highlights :

  1. To ensure maintainable, scalable, and efficient code, it’s essential to follow best coding practices while developing LWC components.
  2. We can improve LWC component performance by using Best Practices of LWC coding.
  3. Use proper name conventions.
  4. Use base components.

Best Practices :

1. Naming Conventions: Always use camel case to name your component and use kebab-case in HTML files when you try to reference any components or child components like the below example for LWC Datatable. Here you can see lightning-datatable base component and in the LWC Datatable key-field, show-row-number-column. Never use the capital letter in these references.

<template>
    <div style="height: 300px;">
        <lightning-datatable
                key-field="id"
                data={data}
                show-row-number-column
                row-number-offset={rowOffset}
                hide-checkbox-column
                columns={columns}>
        </lightning-datatable>
    </div>
</template>

2. Use Base standard components: Use always Base standard LWC components. There are many standard ones like creating complex Datatable, Combobox, buttons. With the small lines of code, we can achieve our goal and also they give us extra functionality.

Base Lightning components are styled with the native Lightning look and feel. These are responsive also. Below is one for select picklist components. We just need to put the given field values and it will automatically work.

<template>
    <lightning-combobox
            name="progress"
            label="Status"
            value={value}
            placeholder="Select Progress"
            options={options}
            onchange={handleChange} ></lightning-combobox>

    <p>Selected value is: {value}</p>
</template>
LWC-base-components

3. Use SLDS CSS class: Try to use SLDS(Salesforce Lightning Design System) for designing in LWC HTML to create beautiful and rich UI experiences for end users.

Try to avoid third parties as much as possible it can be a security issue. SLDS also provides us with design blueprints so we can create our own reusable components which is not possible with Base components like modal, alert, Toast, etc.

4. Reusable JS library – Service components: Many times same JS code repeat in multiple components so we can create a service JS file and reuse this. Like Sorting and Filtering the data.

5. Performance-load the data: Don’t show all data at a time in the LWC component. This will hang our systems also performance also down. To increase performance we can avoid this and can try Pagination to show data in chunks.

Show Spinner when the data load for a better user experience. We can also use tabs to show data.

Check out the below links for more info:

Add Spinner in Lightning Web Component (LWC) Salesforce

Pagination in LWC Datatable Salesforce

6. Use Minified Versions of Libraries and Style Sheets: If you absolutely need to use a third-party library, make sure you use minified versions of the library and style sheet to increase the performance of your components.

7. Use SLDS Icons: You can use the SLDS icon library instead of designing and building your own icons. If you are using icons in your organization, try to reuse them. For example: using the Account, file icons for a custom feature might confuse the users. These icons look and feel the same as Salesforce use in their org.

8. Use UI API for CRUD Operations: If possible try to avoid calling the apex for CRUD operations and use LWC UI API. These are very simple and take less time. We can say this is Low Code and great performance.

you can check out my blog for more info
Use createRecord in LWC Salesforce

Use deleteRecord in LWC Salesforce

9. Use Lightning Data Service: If we don’t need to create multiple records and want FLS direct on the LWC component we can try to use LDS(Lightning Data Service) record form. By record form, we can view, create and edit the record. We don’t need an Apex server call for this. Like lightning-record-edit-form, lightning-record-form, and lightning-record-view-form.

Example: Below form is edit the record by giving the record Id and Object name. We can change the mode with view, and edit.

<lightning-record-form
    record-id={recordId}
    object-api-name={objectApiName}
    fields={fields}
    columns="2"
    mode="edit"
    onsubmit={handleSubmit}
>
</lightning-record-form>

10. Server call Fetching Data: Always try to use @AuraEnabled(cacheable=true) when we just querying the data, no DML operation there. If you have to do any DML operation, then ensure that the cacheable is set to false. While making Apex server calls, retrieve only fields and records that are required.

The first choice of calling apex from the component should be using a wire service. It’s recommended to use a wire service for all your server calls. Unless it’s not possible to use a wire call, make an imperetive apex call.

Call Apex class in LWC Salesforce

11. Reusable components: Try to create a reusable component in place of writing the same code again and again. Like, create a custom lookup LWC component.

Create Reusable Custom Lookup in (LWC) Salesforce

12. Documentation: Document your code and provide clear comments to enhance understandability and maintainability for yourself and other developers. Create documentation for your LWC components, explaining their purpose, usage, and any important considerations. Check out the below link for more info.

Salesforce Development Code Commenting Best Practice

13. Use Error Handling and Debugging: Implement error handling mechanisms such as try-catch blocks to handle exceptions gracefully and provide meaningful error messages to users. Utilize browser developer tools and the Lightning Web Components Inspector to debug and inspect your components during development.

import { LightningElement, api, track } from 'lwc';
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
import getAccounts from '@salesforce/apex/AccountDataController.getAccounts';
export default class DownloadJSONLWC extends LightningElement {
    @track data;

    handleJSONDonwload() {
        this.handleFetchJSONData();
    }

    handleFetchJSONData() {
        getAccounts({})
            .then(res => {
                console.log(res);
                this.data = JSON.stringify(res);
                this.handleDownloadJSONFile();
            }).catch(err => {
                this.showToast('Error', err.body.message, 'error', 'dismissable');
            })
    }
}

14. Event Handling: Use @api decorators, to handle events between components efficiently. By @api we can directly send data from parent to child we just need to mention this in the parent component child definition. If this is not possible then we can call parent-to-child methods and pass prams. For more info, you can check out below links
How to call Parent from child Component In Lightning Web Component (LWC) Salesforce

Call child method from parent component in LWC Salesforce

Output :

Reference :

  1. Lightning Web Components Performance Best Practices
  2. LWC
What’s your Reaction?
+1
5
+1
1
+1
0
+1
0
+1
1
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.