Top Five Best Practices for Lightning Web Components

Top five best practices for Lightning Web Components (LWC)

πŸ‘πŸ½ The following best practices are in order of importance.

# 1 – Always Cache Data

Lightning web components offer two ways to cache data. The first is to use Lightning Data Service, which automatically handles security for you. The best part is that you do not have to write any Apex classes – especially platform required test classes.

If you must use Apex, then you can simply mark your methods as cacheable using the AuraEnabled annotation. The Winter 23 release introduced the global scope option for this annotation.

public static myCacheableMethod() {}

# 2 – Use Conditional Rendering

Conditional rendering means that portions of a component will not be rendered until a condition is met.

For example, let’s assume you had a component that displayed a list of widget data. You would not want the list to be built unless there was data available. If there was no data, then the user would see a message telling them there are no widgets.

<div if:true{widgets}>
   <template for:each={widgets} for:item="widget">
       <li key={widget.Id}>{widget.Name}</li>
<div if:false{widgets.length}>
   There are no widgets available

#3 – Use Pagination with Lists

While we are on the topic of lists, rendering a list of data has the potential for causing lots of performance problems. Many Salesforce orgs have custom objects that contain hundreds, thousands, if not millions of records.

The best way to prevent these lists from getting out of control is to introduce a pagination component. You can see an example of this in the eBikes GitHub repository.


# 4 – Use Base Lightning Web Components

There are now 94 base Lightning web components to choose from. They cover everything from a simple input box to a complex record form.

These components not only offer the CSS from the Salesforce Lightning Design System (SLDS), but they offer a performance advantage. These components are already rendered at the client-side, so they do not require additional download processing.

# 5 – Use SLDS Icons and Styling

And since I mentioned the SLDS, let me remind you that the Lightning Design System website offers hundred of optimized icons. Using your own customized icons can result is low render quality and resolution, so be sure to take advantage to these readily available goodies.

Want to learn more about Lightning Web Components?

Check out my Building your First Lightning Web Component (LWC) course

(There is a new Getting Started course due to be published next month)

Leave a Comment

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

You are commenting using your 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