Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

Best Practices for Writing

Lightning Web Components


(LWC) in Salesforce

sweety kumari
LWC Component Bundle Naming Convention:

Naming conventions are crucial for maintaining a


consistent and readable codebase. In Lightning
Web Components (LWC), different parts of the
component bundle follow specific naming
conventions:

Component Bundle:
Use camelCase: Name your component
bundles using camelCase.
Example: myComponent

HTML File:
Use camelCase: Name the HTML file
using camelCase to match the component
bundle name.

sweety kumari
Use kebab-case: Reference the component
in the markup using kebab-case.
Example: For a component bundle named
myComponent, the HTML file is
myComponent.html and referenced as <c-my-
component></c-my-component>.

<<!-- parentComponent.html -->


<template>
<c-my-component></c-my-component>
</template>

JavaScript File:
Use PascalCase: Name the JavaScript class
in PascalCase.
Example: For a component bundle named
myComponent, the JavaScript file is
myComponent.js with a class named
MyComponent.

sweety kumari
Modular Architecture:

Break down complex components into


smaller, reusable components.
Follow the single-responsibility principle to
enhance maintainability.

Use Lightning Data Service (LDS):

Leverage LDS for CRUD operations instead


of calling Apex directly.
Benefits: Simplified code, built-in caching,
and reduced server round-trips.

sweety kumari
Use @wire for Reactive Properties:

Use @wire decorator for reactive


properties to automatically fetch and
update data.
Ensures efficient data loading and state
management.

Avoid Inline Styles:

Use CSS stylesheets or SLDS (Salesforce


Lightning Design System) for styling.
Enhances consistency and maintainability.

sweety kumari
Import Object & Field References:

Prefer importing schema references using


@salesforce/schema.
Ensures compile-time checking and easier
refactoring.

Example:
import { LightningElement, wire } from 'lwc';
import ACCOUNT_OBJECT
from'@salesforce/schema/Account';
import NAME_FIELD from
'@salesforce/schema/Account.Name';
import getAccountList from
'@salesforce/apex/AccountController.getAccountList';

export default class AccountList extends LightningElement {


accountObject = ACCOUNT_OBJECT;
nameField = NAME_FIELD;

@wire(getAccountList)
accounts;
}

sweety kumari
Error Handling:
Implement robust error handling for Apex
calls and data operations.
Use try-catch blocks and user-friendly error
messages.

sweety kumari

You might also like