Lightning Web Components (LWC): Complete Guide and Interview Questions
Dive into the world of Lightning Web Components (LWC), Salesforce's modern framework for building high-performance UI. This module covers LWC fundamentals, component structure, data flow, event communication, and best practices.
What is a Lightning Web Component?
A Lightning Web Component (LWC) is a Salesforce UI component built with standard HTML, modern JavaScript and CSS on web standards such as custom elements and shadow DOM. Each component has an HTML template, a JavaScript class and a meta XML file. Data flows down through @api properties, events flow up, and @wire or Apex calls load Salesforce data.
- @api exposes a public property or method; @wire reads data reactively; @track is only needed to watch changes inside objects and arrays.
- Lifecycle: constructor, connectedCallback, render, renderedCallback, disconnectedCallback and errorCallback.
- Use Lightning Message Service to talk between components that aren't parent and child.
- Wired Apex methods must be @AuraEnabled(cacheable=true) and can't run DML.
- Lightning Web Security is replacing Lightning Locker for component isolation.
1. Introduction to LWC
Lightning Web Components (LWC) represents Salesforce's modern approach to building user interfaces on the Lightning Platform. Introduced in Spring '19, LWC is a client-side JavaScript framework built on web standards, offering superior performance, a familiar development experience for web developers, and seamless integration with the Salesforce ecosystem.
What is LWC?
LWC is a lightweight, performant framework for building single-page applications and reusable UI components. It leverages modern web standards (ECMAScript 7+, Web Components, Shadow DOM) and provides a thin layer of Salesforce-specific services on top — making LWC development feel much like standard web development.
Why LWC?
- Performance: Built on web standards, LWC is significantly faster than its predecessor Aura Components due to less framework overhead and native browser support.
- Modern Web Standards: Familiarity for web developers, easier to learn, and aligned with industry best practices.
- Reusability: Components are modular and reusable across different parts of your Salesforce org or Experience Cloud sites.
- Encapsulation: Shadow DOM scopes component markup and selectors. Lightning Web Security or Lightning Locker provides additional security isolation.
- Developer Productivity: Modern tooling, clear component lifecycle, and a streamlined development model.
- Coexistence with Aura: LWC and Aura components can coexist and communicate within the same Lightning page, allowing gradual migration.
LWC is the recommended framework for building new UI components on the Salesforce platform. While Aura components are still supported, LWC offers the most benefits for future development.
2. LWC Core Concepts
A UI component is a custom HTML element with JavaScript and an HTML template, and it can include CSS. These files define its behavior, structure, and styling.
a. Component-Based Architecture
LWC promotes a component-based architecture where UIs are broken down into small, independent, and reusable building blocks. Each component manages its own state and renders its own UI, making development modular and maintainable.
b. HTML Template (.html)
Defines the component's UI structure using standard HTML with special LWC directives. Uses a <template> tag as the root.
<template>
<div class="container">
<h1>Hello, {greeting}! Count: {counter}</h1>
<button onclick={handleClick}>Increment Count</button>
</div>
</template>
{property}— Binds data from the JavaScript class to the template.onclick={methodName}— Binds an event to a JavaScript method.lwc:if,lwc:elseif,lwc:else— Conditional rendering.for:each,for:item,for:index— Iterates over a list to render items.
c. JavaScript Class (.js)
Contains the component's logic, data, and event handlers. It's an ES6 module that imports functionalities from the lwc module.
import { LightningElement, api } from 'lwc';
export default class HelloWorld extends LightningElement {
@api greeting = 'World'; // Public input owned by the parent
counter = 0; // Private component state
connectedCallback() {
console.log('Component is connected to the DOM!');
}
handleClick() {
this.counter++;
}
}
import { LightningElement } from 'lwc';— Imports the base class for LWC.export default class ... extends LightningElement— Defines the component's JavaScript class.- Decorators (
@api,@track,@wire) — Special annotations that add reactive or public capabilities to properties.
d. CSS (.css)
In shadow DOM, component CSS selectors are scoped to the component, but inherited values and CSS custom properties can cross the shadow boundary. Light DOM has different scoping rules, and unscoped styles can affect other elements.
.container {
padding: 20px;
border: 1px solid rgba(255,255,255,.06);
border-radius: 8px;
text-align: center;
}
h1 {
color: #0070d2;
font-size: 2em;
}
button {
background-color: #0070d2;
color: white;
border: none;
padding: 10px 20px;
border-radius: 5px;
cursor: pointer;
}
3. LWC Component Structure
A UI component bundle resides in a folder with the component name and includes HTML, JavaScript, metadata, and optionally CSS. An API module that shares JavaScript functionality does not require an HTML template.
Standard Folder Structure
force-app/main/default/lwc/
└── myComponentName/
├── myComponentName.html
├── myComponentName.js
├── myComponentName.css (Optional)
└── myComponentName.js-meta.xml
myComponentName.html— Defines the component's user interface.myComponentName.js— Contains the component's logic, properties, and event handlers.myComponentName.css— Optional scoped styles (Shadow DOM encapsulated).myComponentName.js-meta.xml— Defines API version, exposure targets, and object restrictions.
Example js-meta.xml
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>58.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
<target>lightning__RecordPage</target>
<target>lightning__HomePage</target>
</targets>
<targetConfigs>
<targetConfig targets="lightning__RecordPage">
<objects>
<object>Account</object>
<object>Contact</object>
</objects>
</targetConfig>
</targetConfigs>
</LightningComponentBundle>
apiVersion— Specifies the API version for the component.isExposed— Set totrueto make the component available in Lightning App Builder or Experience Builder.targets— Defines where the component can be used (App Page, Record Page, Home Page, etc.).targetConfigs— Provides specific configurations per target, such as restricting usage to certain sObjects on a record page.
4. Data Flow & Decorators (@api, @track, @wire)
LWC uses decorators to enable reactivity and public properties in JavaScript classes. These are imported from the lwc module and play a crucial role in how data flows within and between components.
a. @api — Public Properties
- Purpose: Exposes a property as public. Parent components can set its value on a child component. Changes are reactive.
- Use Cases: Passing data down from parent to child component. The owner controls a public input; a child can keep its own mutable state or dispatch an event requesting an update.
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api recordId;
@api message = 'Default Message';
}
<c-child-component record-id="001..." message="Hello from Parent"></c-child-component>
b. @track — Reactive Private Properties
- Purpose: Observes mutations within plain objects and arrays. A mutation triggers rerendering only when it affects a property accessed during the previous render.
- Important: Since Spring '20, fields are shallow-reactive by default. Use
@trackwhen observing internal mutations of plain objects or arrays; assigning a new value is observed without it.
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track myObject = { name: 'Initial', value: 0 };
updateObject() {
// A render that accessed myObject.value can reflect this mutation.
this.myObject.value += 1;
}
}
c. @wire — Reactive Data Service
- Purpose: Provisions data from an Apex method or wire adapter to a property or function. Changes to reactive parameters trigger reprovisioning; stale Apex data requires
refreshApex()on the retained wire result. - Use Cases: Fetching records, getting picklist values, querying Apex methods reactively.
import { LightningElement, wire } from 'lwc';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
export default class AccountList extends LightningElement {
@wire(getAccounts)
accounts; // { data, error } auto-provisioned
// Or use a function for more control:
// @wire(getAccounts)
// wiredAccounts({ error, data }) {
// if (data) { this.accounts = data; }
// else if (error) { this.error = error; }
// }
}
5. Event Communication
Components in LWC communicate primarily through events. Understanding event flow is crucial for building interactive applications where components need to interact with each other.
a. Child-to-Parent Communication (Custom Events)
Children dispatch custom events; parents listen for them. This is the recommended way for a child to notify its parent of an action or data change. For this direct listener, the default values of bubbles and composed are both false.
import { LightningElement } from 'lwc';
export default class ChildComponent extends LightningElement {
handleClick() {
const myCustomEvent = new CustomEvent('childclick', {
detail: 'Hello from child!'
});
this.dispatchEvent(myCustomEvent);
}
}
<template>
<p>Message from child: {childMessage}</p>
<c-child-component onchildclick={handleChildClick}></c-child-component>
</template>
import { LightningElement } from 'lwc';
export default class ParentComponent extends LightningElement {
childMessage = '';
handleChildClick(event) {
this.childMessage = event.detail;
}
}
b. Parent-to-Child Communication
Parents pass data down to children using @api public properties — covered in the decorators section above.
c. Unrelated Components — Lightning Message Service (LMS)
For components not in a direct parent-child relationship (e.g., on different parts of a Lightning page), Lightning Message Service (LMS) is the recommended solution using a publish-subscribe model.
import { LightningElement, wire } from 'lwc';
import { publish, MessageContext } from 'lightning/messageService';
import SAMPLE_MESSAGE_CHANNEL from '@salesforce/messageChannel/SampleMessageChannel__c';
export default class PublisherComponent extends LightningElement {
@wire(MessageContext) messageContext;
publishMessage() {
const payload = { recordId: '001ABC', message: 'Data updated!' };
publish(this.messageContext, SAMPLE_MESSAGE_CHANNEL, payload);
}
}
import { LightningElement, wire } from 'lwc';
import { subscribe, unsubscribe, MessageContext } from 'lightning/messageService';
import SAMPLE_MESSAGE_CHANNEL from '@salesforce/messageChannel/SampleMessageChannel__c';
export default class SubscriberComponent extends LightningElement {
subscription = null;
receivedMessage = '';
@wire(MessageContext) messageContext;
connectedCallback() {
this.subscription = subscribe(
this.messageContext,
SAMPLE_MESSAGE_CHANNEL,
(message) => { this.receivedMessage = message.message; }
);
}
disconnectedCallback() {
unsubscribe(this.subscription);
this.subscription = null;
}
}
6. LWC Lifecycle Hooks
LWC components have a well-defined lifecycle, and you can tap into specific phases using lifecycle hooks — methods in the component's JavaScript class that execute at particular moments.
constructor()— Called when the component is created. Always callsuper()first. Do not access@apiproperties orthis.templatehere — they are not yet initialized. Use for initializing private properties.connectedCallback()— Called when the component is inserted into the DOM. Use for fetching initial data (if not using@wire), setting up event listeners, and accessing@apiproperties. Fires again if component is removed and reinserted.renderedCallback()— Called after every render (initial and re-renders). Use for DOM manipulations or integrating third-party libraries. Be cautious — avoid updating reactive properties here without a guard condition to prevent infinite loops.disconnectedCallback()— Called when the component is removed from the DOM. Use for cleanup: removing event listeners, unsubscribing from LMS to prevent memory leaks.errorCallback(error, stack)— Catches descendant errors in lifecycle hooks and declaratively assigned event handlers. It does not catch errors in programmatically assigned event handlers. Use it as an error boundary for logging and fallback UI.
import { LightningElement, api } from 'lwc';
export default class LifecycleDemo extends LightningElement {
@api recordId;
constructor() {
super();
console.log('1. Constructor called');
// Do NOT access this.recordId or this.template here
}
connectedCallback() {
console.log('2. Connected Callback — Record ID:', this.recordId);
}
renderedCallback() {
console.log('3. Rendered Callback');
// Guard against infinite loops:
// if (!this.hasRendered) { this.hasRendered = true; ... }
}
disconnectedCallback() {
console.log('4. Disconnected Callback — clean up resources');
}
errorCallback(error, stack) {
console.error('5. Error Callback:', error, stack);
}
}
7. Working with Apex in LWC
LWC can interact with Salesforce data and logic stored in Apex classes — allowing complex database operations, business logic, and callouts not possible in client-side JavaScript alone.
a. Apex Method Requirements
An Apex method exposed to LWC must be static, public or global, and annotated with @AuraEnabled. A wired Apex method also requires cacheable=true. The user must have access to the Apex class.
public with sharing class AccountController {
@AuraEnabled(cacheable=true)
public static List<Account> getAccounts() {
return [SELECT Id, Name, Industry FROM Account WITH USER_MODE LIMIT 10];
}
@AuraEnabled(cacheable=true)
public static List<Account> getAccountDetails(Id accountId) {
return [SELECT Id, Name, Industry FROM Account
WHERE Id = :accountId WITH USER_MODE];
}
@AuraEnabled
public static Id createAccount(String accountName) {
if (String.isBlank(accountName)) {
throw new AuraHandledException('Account name is required.');
}
Account newAcc = new Account(Name = accountName);
insert as user newAcc;
return newAcc.Id;
}
}
b. Calling Apex Imperatively
Use an imperative call when you need explicit control over execution, such as for a button-triggered insert. It returns a Promise. This example waits for the wired read to return data, then refreshes its retained result after the insert. A UI can also disable the create action until the read succeeds.
import { LightningElement, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getAccounts from '@salesforce/apex/AccountController.getAccounts';
import createAccount from '@salesforce/apex/AccountController.createAccount';
export default class ApexImperativeDemo extends LightningElement {
accounts;
wiredAccountsResult;
error;
@wire(getAccounts)
wiredAccounts(result) {
this.wiredAccountsResult = result; // Retain the complete result.
this.accounts = result.data;
if (result.error) {
this.error = result.error;
}
}
async handleCreateAccount() {
try {
if (!this.wiredAccountsResult || !this.wiredAccountsResult.data) {
throw new Error('Load accounts before creating an account.');
}
const accountId = await createAccount({ accountName: 'New Imperative Account' });
console.log('Account created with ID:', accountId);
await refreshApex(this.wiredAccountsResult);
this.error = undefined;
} catch (error) {
this.error = error;
}
}
}
c. Calling Apex with @wire (Reactive)
Use @wire to provision read-only Apex data. The $ prefix makes a parameter reactive, so a change to that parameter triggers reprovisioning. A server-side change alone does not guarantee a fresh Apex result.
import { LightningElement, api, wire } from 'lwc';
import getAccountDetails from '@salesforce/apex/AccountController.getAccountDetails';
export default class AccountDetailsWire extends LightningElement {
@api recordId;
accounts;
error;
@wire(getAccountDetails, { accountId: '$recordId' }) // '$' makes it reactive
wiredAccount({ error, data }) {
if (data) {
this.accounts = data;
this.error = undefined;
} else if (error) {
this.error = error;
this.accounts = undefined;
}
}
}
Choose imperative when you need controlled execution, including DML. Choose @wire for declarative read-only provisioning driven by reactive parameters. Retain the complete Apex wire result and pass it to refreshApex() when the data becomes stale.
How do you choose a data service and refresh its cache?
Use Lightning Data Service (LDS) and UI API adapters for supported record operations, or a GraphQL wire adapter when its query model fits the data. Use Apex when those services cannot provide the required operation or business logic. LDS manages record access and its record cache; Apex data has a separate cache. When an Apex wire result is stale, pass the complete retained result to refreshApex(). After records change outside LDS, call notifyRecordUpdateAvailable() with the affected record IDs so LDS can refresh its cached records. The lightning/graphql wire result provides its own refresh() method.
8. LWC Best Practices
Adhering to best practices ensures your Lightning Web Components are performant, maintainable, secure, and reusable.
a. Component Granularity
- Small, Focused Components: Design components to do one thing well. Break complex UIs into smaller, reusable child components.
- Container vs. Presentational: Container components handle data fetching and logic; presentational components focus solely on rendering UI based on input properties.
b. Data Flow & Reactivity
- Unidirectional Data Flow: Data flows down via
@api; events flow up via custom events. - Minimize
@track: Only use for objects/arrays needing internal property reactivity. Primitives are auto-reactive. - Choose a Data Access Pattern: Use wire adapters for declarative reads and imperative calls when execution must be controlled explicitly, including for DML.
c. Performance
- Lazy Loading: Load data or components only when needed.
- Minimize DOM Manipulation: Let the framework handle DOM updates. Avoid
this.template.querySelectorwithout guards inrenderedCallback. - Optimize Apex Calls: Ensure Apex methods are bulkified and selective to avoid governor limits.
d. Security
- Enforce Permissions: UI API respects record access, object permissions, and field-level security. In Apex, enforce applicable permissions for user-facing operations using explicit user-mode queries and DML or
stripInaccessible(), as appropriate. Sharing alone does not enforce object or field permissions. - Validate User Input: Validate input for the operation, use bind variables for SOQL, and enforce authorization and field permissions for DML.
How do Lightning Web Security and CSP protect components?
Lightning Web Security (LWS) isolates JavaScript by namespace, while Content Security Policy (CSP) restricts permitted resource loads and connections. LWS is the default for new orgs; some older orgs still use Lightning Locker. Both security architectures place restrictions on component code and access across namespaces, but their behavior differs, so test integrations under the architecture enabled in the org. Configure trusted URLs where appropriate, and load third-party libraries from static resources according to Salesforce guidance. Shadow DOM encapsulation is separate from these security controls and should not be treated as an authorization boundary.
e. Reusability & Maintainability
- Clear Naming Conventions: Use consistent, descriptive names for components, properties, methods, and events.
- Comments: Document complex logic and non-obvious parts of the code.
- Use Lightning Base Components: Utilize standard
lightning-components (e.g.,lightning-button,lightning-input,lightning-datatable) — they are performant, accessible, and SLDS-compliant.
How do you make component interactions accessible?
Use semantic HTML and Lightning base components, and provide clear labels for controls. Ensure every action is operable with a keyboard and that focus moves predictably when content such as a dialog opens or closes. Expose state and errors to assistive technology using appropriate native semantics and ARIA attributes where needed. Do not rely on color alone to convey information. Test with keyboard navigation and a screen reader, including validation messages and dynamically updated content. Custom interactive controls need the expected keyboard behavior and an accessible name, role, and state.
f. Testing
- Write Jest Unit Tests: Use Jest for client-side LWC unit testing to verify component behavior in isolation.
- Test Apex Integration: Ensure all Apex methods called by LWC are covered by Apex unit tests.
9. Conclusion & Next Steps
Lightning Web Components provide a powerful, modern, and efficient framework for building rich user interfaces on the Salesforce platform. By embracing web standards and offering robust features for data binding, event communication, and Apex integration, LWC empowers developers to create highly performant and maintainable applications.
Key Takeaways
- Web Standards First: LWC is built on modern web standards, making it approachable for web developers.
- Component-Based: Focus on building small, reusable, and encapsulated components.
- Decorators are Key: Understand
@apifor public properties,@trackfor reactive objects/arrays, and@wirefor reactive data provisioning. - Event-Driven Communication: Use custom events for child-to-parent and LMS for unrelated component communication.
- Lifecycle Awareness: Leverage lifecycle hooks to execute code at specific points in a component's life.
- Apex Integration: Seamlessly connect to Apex for server-side logic and data operations.
- Best Practices: Prioritize performance, security, reusability, and thorough testing.
Mastering LWC is essential for any Salesforce developer looking to build modern, engaging, and scalable user experiences. Continue exploring the official Salesforce LWC Developer Guide and Trailhead modules for deeper dives into advanced topics and real-world scenarios.
Frequently asked questions
What is the difference between @api, @track and @wire?
@api makes a property or method public so a parent component can set or call it. @wire connects a property or function to a data source, such as an Apex method or a Lightning Data Service adapter, and refreshes it when its parameters change. @track is now needed only to observe changes inside an object or array, because all fields are reactive by default.
When should you use wire versus an imperative Apex call?
Use @wire for read-only data that should load and refresh automatically; the Apex method must be cacheable=true. Use an imperative call when you need to run DML, control exactly when the call happens, or call it in response to a user action.
How do sibling LWC components communicate?
Through a shared parent that listens for an event from one child and passes data down to the other, or through Lightning Message Service when the components are unrelated or on different parts of the page.
What is the order of LWC lifecycle hooks?
constructor runs first, then connectedCallback when the component is inserted into the DOM, then render and renderedCallback after each render. disconnectedCallback runs when it is removed, and errorCallback runs in a parent when a child throws an error.
What is Lightning Web Security?
Lightning Web Security (LWS) is Salesforce's newer security architecture for components. It isolates each namespace in its own JavaScript sandbox, allows more standard web APIs than Lightning Locker, and is replacing Locker for LWC.