Lightning Web Component

A Guide through LWC Best Practices

Following the LWC Best Practices development not only helps in creating a better environment for you but also for other developers who might work with them in the future.

These practices include setting up your development environment, optimizing performance, and ensuring security.

Best Practices in Lightning Web Components

Structure your LWC Project

Organizing your Lightning Web Component (LWC) project effectively is the first step in ensuring code maintainability, scalability, and collaboration with fellow developers. A well-structured project not only makes your life easier but also sets the foundation for a successful development journey.

Naming Conventions

Example: contactList, opportunityDetail, customAccordion.

Reusability

Example

Before you start coding your component, it's always a good practice to create a model of your complete component. Here is an example model of a product selection component that allows the members to select a product from your Salesforce organization using all the best practices mentioned above.

Follow the best practices to structure your LWC in Salesforce

HTML & CSS Best Practices

HTML and CSS best practices play a crucial role in creating efficient, maintainable, and performant LWC in Salesforce. Adhering to these practices ensures that your code is clean, readable, and follows industry standards.

HTML

<template>
    <header if:true={showHeader}>
        <h1 class="pselection-title">Select your products</h1>
    </header>
    <main class="pselection-container">
        <c-product-selection-filter></c-product-selection-filter>
        <c-product-selection-card></c-product-selection-card>
    </main>
    <footer>
        <lightning-button label='Confirm Products' onclick={handleConfirm}>
        </lightning-button>
    </footer>
</template>

CSS

.pselection-container{
    padding: 30px;
    margin: 0;
    color: black;
}

.pselection-title{
    font-size: 1.5rem;
    font-weight: bold;
}

/* STYLES FOR MOBILE */
@media (max-width: 480px) {
    .pselection-container{
        padding: 20px;
    }
}

Coding on JavaScript

About the LWC Coding Best Practices, maintaining consistent coding standards is essential for creating clean, readable, and maintainable JavaScript code within your LWC. Adhering to a set of coding standards helps streamline development, promotes collaboration among team members, and reduces the chances of introducing bugs.

Data Management

They often interact with Salesforce data, understanding best practices of LWC for handling and manipulating data is crucial.

Data Fetching

Always using the @wire service is the best choice to retrieve data from Salesforce to display in your LWC. While imperative Apex method calls are possible, it's better decision to use @wire because it ensures efficient server to client communication

export default class wireExample extends LightningElement {
    @wire(getContacts)
    contacts;

    fetchData() {
        getContacts()
            .then(result => {
                this.contacts = result;
            })
            .catch(error => {
                // Handle errors
            });
    }
}

Data Transformation

Whenever possible, transform the data on the client-side to reduce server load and increase responsiveness. You can use a lot of Javascript methods such as: some(), map(), filter() etc. I will let you some examples here using this Javascript object:

const data = [
    {
        "firstName": "John",
        "lastName": "Doe",
        "age": 27
    },
    {
        "firstName": "Martin",
        "lastName": "Smith",
        "age": 10
    }
]

some(): it returns true or false depending if the element on the array it's found.

data.some(item => item.firstName == 'John') // TRUE
data.some(item => item.age == 30) // FALSE

map(): it return a new array but you can execute a function for each element.

data.map(item => new Date().getFullYear() - item.age) // [1996, 2013]

filter(): return a new array with all the elements that matches on the function specified

data.filter(item => item.age == 10) 
    // [{ firstName: "Martin", lastName: "Smith", age: 10 }]

Pagination and Lazy Loading

When dealing with large data sets, implement pagination to load data in smaller, manageable chunks. Additionally, load data as needed, especially for lists or tables

Data Synchronization

Ensure that data displayed in your LWC is kept in sync with any updates or changes made to the data in Salesforce. For real-time updates, consider using Lightning Message Services to notify your components of data changes.

Performance Optimization

Make sure that your LWC perform efficiently is crucial for provide to the user an responsive and user-friendly experience in Salesforce. So we will give some LWC Performance Best Practices