Salesforce Lightning Web Components (LWC) is a modern way to build reusable components for Salesforce platform, making it a HOT topic for interviews.
To help you prepare, we’ve compiled a list of 20 interview questions covering basic, intermediate, and advanced concepts of LWC.
So, without wasting more time, let’s start…
1. What is Salesforce Lightning Web Components (LWC)?
Salesforce Lightning Web Components (LWC) is a modern way to build reusable components for Salesforce using JavaScript.
It follows latest web standards, making it faster, easier, and more flexible than the older Aura framework.
LWC helps Salesforce developers to create user interface (UI) components more efficiently and with better performance.
Key Features of LWC are:
-
- LWC is built on Latest Web Standards.
- Performance of LWC is Faster and Lightweight than Aura components.
- LWC components have the ability to be reused in other LWC components within same organization.
- While developing a LWC component, developers can create each component independently and then compose them together to build complex UIs.
- It enhances Developer’s Productivity.
- Developers can easily Integrate LWC with Salesforce Platform.
- Reactivity – Meaning when data changes in Salesforce backend, the LWC UI is automatically updated to reflect those changes
- Apex Integration – LWC can be integrated with Apex to handle business logic and to perform DML operations.
Apex integration to LWC can be done in 2 ways : using @wire and imperative approach.
If you want to learn more about Salesforce LWC, then I would recommend you to explore the post below.
2. What are the advantages of using LWC over Aura Components?
- Better Performance: LWC is faster than Aura components because it uses modern web standards like JavaScript ES6, which are optimized by browsers.
This results in faster rendering and better overall performance. - Simpler Syntax:
LWC uses a cleaner, simpler syntax based on standard JavaScript and HTML, making it easier to learn and work with compared to the more complex Aura syntax. - Smaller Bundle Size:
LWC components are lightweight, leading to smaller bundle sizes, which reduces the amount of data that needs to be loaded, improving load times. - Modern Web Standards:
LWC is built on web standards like custom elements, Shadow DOM, and ES modules, making it more compatible with other frameworks and easier for developers to use modern tools and libraries. - Reactivity:
LWC has built-in reactivity, meaning that when data changes, the UI updates automatically without needing extra code, making it easier to manage dynamic content. - Better Developer Experience:
With LWC, developers can take advantage of features like easier debugging, better integration with tools like Jest for testing, and better support for browser features. - Component Isolation:
LWC uses Shadow DOM.
This keeps the component’s structure, style, and behaviour separate, so they don’t affect the rest of the page.
- Better Performance: LWC is faster than Aura components because it uses modern web standards like JavaScript ES6, which are optimized by browsers.
In short, LWC provides better performance, simplicity, and developer experience compared to Aura components, making it the preferred choice for building Salesforce applications.
3. Explain the LWC component folder structure
In Salesforce, every LWC component is stored in its own folder, which contains files that control its behaviour, appearance, and functionality.
Here are the types of files you’ll find in an LWC component folder.
1. HTML File (componentName.html):
This file contains the structure of your LWC component. It defines the layout using HTML tags.
2. JavaScript File (componentName.js):
Javascript file contains the logic for your LWC component.
It defines the behaviour using JavaScript, such as handling user events or making data requests.
3. CSS File (componentName.css): (optional)
CSS file contains the styling for your component. It controls the look and feel of the component, like colours, fonts, and layout.
4. Meta File (componentName.xml)
This file contains the configuration details about the component.
In this file, we define things like the component’s visibility, target audience, and where it can be used (e.g., in Lightning Pages, record pages, etc.).
Example Folder Structure
4. What is a shadow DOM, and how is it used in LWC?
Shadow DOM is a web technology that lets you keep your LWC component separate from the rest of the webpage.
It creates a hidden “shadow” tree inside your component, ensuring its structure, styles, and behaviour don’t affect or get affected by other parts of the page.
This prevents conflicts with other parts of the webpage.
Properties of Shadow DOM
- Isolation:
The styles and DOM inside the component are completely separate from the rest of the page. This prevents style conflicts or JavaScript interactions with other components. Component Integrity:
Since each LWC component has its own shadow DOM, changes in one component won’t affect others, making components more predictable and easier to maintain.
Important:
Shadow DOM ensures that – If you define some CSS styles in your LWC component, those styles won’t accidentally change the appearance of other elements on the page
Explore the post below to learn more about Shadow DOM Boundaries in LWC
5. What are the prerequisites for developing LWC components?
To start developing Lightning Web Components (LWC), you need a few basic things in place:
- Salesforce Account:
- You need access to a Salesforce organization (Org), either a Developer Edition, a Sandbox, or a Salesforce Trailhead Playground to create and test LWC components.
- Basic Knowledge of Web Development:
- •You should be familiar with core web technologies:
- •HTML: For structuring the component.
- •CSS: For styling the component.
- •JavaScript: The logic of your component is present in the JavaScript file.
- •You should be familiar with core web technologies:
- Salesforce Platform Basics:
- •Understanding Salesforce concepts like Objects, Fields, and Apex (for backend logic) will be helpful.
- Salesforce Developer Tools:
- •Salesforce CLI: A command-line interface to interact with Salesforce Org.
- •VS Code: A text editor with Salesforce extensions for developing and deploying LWC components.
- Salesforce Lightning Design System (SLDS) (optional):
- Knowledge of SLDS helps in designing consistent user interfaces that match Salesforce’s design guidelines.
6. Explain the use of @track in LWC
The @track decorator in LWC is used to make a JavaScript property Reactive.
When you add @track to a property, any changes to that property in the JavaScript code, the component’s UI gets automatically updated.
This means your LWC component will re-render whenever the tracked property’s value changes.
Please Note:
- The @track decorator ensures reactivity within the component, but it does not directly track changes from the Salesforce backend.
- If the data is coming from the backend, you would need to handle it (e.g., using Apex methods or data services) and then update the tracked property.
For Example:
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track name = 'John'; // This property is now reactive
}
In Simple Words:
The @track decorator tells the LWC to watch the property for any changes. If there are any changes to the property, then update the LWC component’s UI automatically.
Explore the post below to learn more about @track Decorator in LWC
7. What is the difference between @track, @api, and @wire in LWC?
@track, @api and @wire are 3 different decorators used in Salesforce LWC.
1. @track
- Purpose: Makes a property reactive so that when its value changes in your Javascript code, the component’s UI automatically updates.
- Use case: Used for internal properties that you want to track and update in your component.
Example:
//JavaScript code
@track name = 'John'; // UI updates when 'name' changes
2. @api
- Purpose: @api is used to expose a property or method in a LWC component, allowing it to be accessed by other components, such as parent components or sibling LWC components.
- Use case: @api is used in Child component, when you want to:
Pass data from the Parent component to the Child component.
Call methods in the Child component from the Parent.
Example:
Parent Component (HTML):
Child Component (JavaScript):
import { LightningElement, api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api messageFromParent; // Property exposed to parent
}
Child Component (HTML):
{messageFromParent}
In this example:
- The parent LWC component passes a message (message-from-parent) to the child LWC component.
- The child component uses @api to define a property (messageFromParent) that receives the value.
- The message is displayed in the child component’s UI.
3. @wire
- Purpose: @wire is used to read data from Salesforce (like from Apex or a REST API) and automatically updates the component when the data changes.
- Use case: It is used for fetching data from Salesforce or invoking Apex methods in a reactive way.
Example:
@wire(getContacts) contacts; // Automatically fetches data
In Summary
- @track: is used to make a property reactive.
- @api: is used to expose Child LWC component’s properties or methods to parent components.
- @wire: is used to fetch and automatically update data from Salesforce or to invoke Apex class.
Explore the post below to learn more about 3 Decorators in Salesforce LWC
8. How do you pass data between parent and child components in LWC?
In Salesforce LWC, you can pass data between parent and child components in two main ways:
1. From Parent to Child (Using Properties):
- The parent component passes data to the child component through HTML attributes.
- The child component receives the data using @api to expose the property.
Parent Component – HTML
Child Component – JavaScript
import { api } from 'lwc';
export default class ChildComponent extends LightningElement {
@api data; // Receives data from parent
}
Explore the post below to learn more about @api Decorator in Salesforce LWC
2. From Child to Parent (Using Custom Events):
- The child component can send data to the parent component by firing a custom event with data.
- The parent listens for the event and handles the data.
Child Component – JavaScript
import { LightningElement } from 'lwc';
export default class ChildComponent extends LightningElement {
handleClick() {
const event = new CustomEvent('childEvent', { detail: 'Data from Child' });
this.dispatchEvent(event); // Sends data to parent
}
}
Parent Component – HTML and JavaScript
export default class ParentComponent extends LightningElement {
handleChildData(event) {
console.log(event.detail); // Receives data from child
}
}
In Summary:
- Parent to Child: Use @api in Child Component to pass data via properties.
- Child to Parent: Use Custom Events to send data via events.
Explore the post below to learn more about Custom Events in Salesforce LWC
9. What are the limitations of LWC compared to Aura Components?
1. Browser Support:
LWC requires modern browsers (Chrome, Firefox, etc.) and doesn’t work well with older browsers like Internet Explorer 11, which Aura supports.
2. Limited to Lightning Experience:
LWC is mainly for Salesforce Lightning Experience and doesn’t support Salesforce Classic, while Aura components can work in both Lightning Experience and Classic.
3. No Public Lightning Event Support:
LWC doesn’t support lightning events like Aura components.
LWC uses Custom Events for communication instead, which is more restricted than Aura’s event system.
4. No Application-Level Access:
In LWC, components can’t have the same application-level access as Aura components.
For example, in Aura, you can use application events to communicate globally across the app, but in LWC, communication is more restricted to parent-child relationships.
5. Limited Support for Dynamic Components:
LWC doesn’t provide native support for dynamic component creation (like Aura’s createComponent), which allows dynamically creating components at runtime in Aura.
In Summary
LWC is faster, simpler, and modern, but it has some limitations in terms of browser support, flexibility in communication, and features available in Aura components.
However, LWC is the recommended choice for new development in Salesforce.
10. How does data binding work in LWC?
In Lightning Web Components (LWC), data binding is the connection between the JavaScript data and the HTML UI, ensuring that – changes in one, updates the other.
Types of Data Binding in LWC:
1. One-Way Data Binding:
- In case of One-Way Binding, data flows from the JavaScript file to the HTML template.
- It is used for displaying values in the UI. From UI, user cannot update the data.
- Changes in JavaScript automatically reflect in the UI, but the reverse is not true.
- Example:
// MyComponent.js
export default class MyComponent extends LightningElement {
message = 'Hello, World!';
}
{message}
2. Two-Way Data Binding:
- In case of Two-Way Binding, data flows both ways between the JavaScript and HTML.
- Two-Way Binding is achieved using input fields with the value attribute and event handlers.
- Example:
// MyComponent.js
export default class MyComponent extends LightningElement {
message = 'Hello';
handleInputChange(event) {
this.message = event.target.value; // Updates JavaScript when input changes
}
}
{message}
Summary
- One-Way Binding: Data flows from JavaScript to the UI (read-only in the UI).
- Two-Way Binding: Data flows back and forth between the JavaScript and the UI, like when you type in an input box.
11. What are Reactive properties in LWC? How do they function?
Reactive properties in Lightning Web Components (LWC) are JavaScript properties that automatically update the component’s UI when their value changes.
How Do They Function?
- Automatic UI Updates:
- When the value of a reactive property changes, LWC automatically re-renders the part of the UI that uses that property.
- No Manual DOM Updates:
- Developers don’t need to write extra code to update the UI, LWC handles it for you.
- How to Declare:
- Simply define a property in the component’s JavaScript file.
- If the property is used in the HTML file, it becomes reactive.
Example
// myComponent.js
export default class MyComponent extends LightningElement {
message = 'Hello, World!'; // Reactive property
updateMessage() {
this.message = 'Hello, LWC!'; // UI will update automatically
}
}
{message}
In Simple Words
- Reactive properties automatically sync changes between the JavaScript and the UI.
- When the property’s value changes, the UI updates without any extra code.
12. How do you include CSS in your LWC Component?
You can easily insert CSS in your LWC component, just follow the below steps.
1. Add a CSS File:
- Create a file with the same name as your component, but with a .css extension.
- Place this file in the same folder as your LWC component’s folder.
Example:
If your component name is ‘myComponent’, the CSS file will be myComponent.css.
2. Write Your Styles:
- •Add your CSS rules inside the .css file.
Example (myComponent.css):
p {
color: blue;
font-size: 16px;
}
3. CSS Applies Automatically:
- The styles in the .css file apply only to the component because of Shadow DOM, so they won’t affect other components or the page.
4. Use Salesforce Lightning Design System (SLDS) (Optional):
- If you want to use Salesforce-specific styles, use SLDS classes in your component’s HTML file.
Example:
Styled with SLDS
In Simple Words:
- Create a .css file in your component folder.
- Write styles in it, and they’ll only apply to that component. Use SLDS for Salesforce’s standard look.
13. What are LifeCycle Hooks in LWC?
Lifecycle hooks in Lightning Web Components (LWC) are special methods that run automatically at different stages of a component’s life (such as – creation, rendering, and removal). They allow you to execute code at specific points in the component’s lifecycle.
Key Lifecycle Hooks:
1. Constructor
- Constructor is the first LifeCycle Hook in LWC.
- It runs when the component is created.
- It is used to initialize properties or set up state.
Example:
constructor() {
super();
console.log('Component created!');
}
2. connectedCallback()
- connectedCallback() is the 2nd method in the LifeCycle Hook of LWC.
- It runs when the component is added to the DOM (displayed on the page).
- It is used to fetch data or interact with the DOM.
Example:
connectedCallback() {
console.log('Component added to the DOM!');
}
3. renderedCallback()
- renderedCallback is the 3rd method in LWC LifeCycle hook.
- It runs after the component’s template is rendered in the DOM.
- It is used to handle post-rendering tasks, like interacting with DOM elements.
Example:
renderedCallback() {
console.log('Component rendered!');
}
4. disconnectedCallback()
- disconnectedCallback is the 4th method in LWC LifeCycle hook
- It runs when the component is removed from the DOM.
- It is used to cleanup tasks, like removing event listeners etc.
Example:
disconnectedCallback() {
console.log('Component removed from the DOM!');
}
In Simple Words:
Lifecycle hooks are methods that let you run specific code when:
- The component is created (constructor).
- It is added to the page (connectedCallback).
- It finishes rendering (renderedCallback).
- It is removed from the page (disconnectedCallback).
Explore the post below to learn more about LifeCycle Hooks in Salesforce LWC
14. What is the purpose of connectedCallback() in LWC?
The connectedCallback() method in Lightning Web Components (LWC) runs automatically when the component is added to the DOM (that is – when the component is displayed on the page).
Purpose:
Perform actions that need to happen when the component loads, like:
- Fetching data from Salesforce or external APIs.
- Setting up event listeners.
- Initializing properties based on external inputs.
Example
connectedCallback() {
console.log('Component is added to the DOM!');
this.fetchData(); // Call a method to load data
}
In Simple Words
The code written inside connectedCallback() runs automatically when the component appears on the screen.
Explore the post below to learn more about the Role and Properties of connectedCallback() in Salesforce LWC
15. What is the significance of renderedCallback() in LWC?
The renderedCallback() method in Lightning Web Components (LWC) runs automatically after the component’s HTML template is rendered in the DOM.
Significance
renderedCallback() is used to perform actions that need to happen after the UI is fully loaded, like:
- Interacting with DOM elements.
- Applying custom styles or calculations.
- Running code that depends on the rendered structure.
Important points:
- It may run multiple times if the component re-renders (e.g., when reactive properties change).
- To avoid running code repeatedly, use a flag to check if the logic has already been executed.
Example
renderedCallback() {
if (!this.isRendered) {
console.log('Component rendered for the first time!');
this.isRendered = true; // Prevent repeated logic
}
}
In Simple Words:
renderedCallback() is used for tasks that need the component’s UI to be fully built before they can run.
Explore the post below to learn more about the Role and Properties of renderedCallback() in Salesforce LWC
16. How can you use JavaScript modules in LWC?
In Lightning Web Components (LWC), you can use JavaScript modules to organize and reuse code efficiently.
Steps to Use JavaScript Modules in LWC:
1. Create a JavaScript Module:
- Create a .js file to define reusable functions, constants, or classes.
- Place it in the modules folder (custom modules) or utils folder (utility code).
Example (utils.js):
export function add(a, b) {
return a + b;
}
2. Export the Code:
- Use the export keyword to make functions, variables, or classes available for other files.
3. Import the Module in LWC:
- Use the import keyword to use the module in your component’s JavaScript file.
Example (Importing utils.js in LWC):
import { add } from './utils.js';
export default class MyComponent extends LightningElement {
result = add(2, 3); // Uses the imported function
}
Benefits
- Keeps code organized and reusable.
- Reduces duplication by centralizing shared logic.
In Simple Words:
- Write reusable code in a separate .js file.
- Use export to make it available and import to use it in your LWC components.
17. What are decorators in LWC? Why they are used?
Decorators in Lightning Web Components (LWC) are special keywords (like @api, @track, and @wire) used to add specific functionality to JavaScript properties or methods.
Why Decorators are used?
Decorators in LWC define – how a property or method should behave in the LWC framework. They help in:
- Exposing Data to Other Components: Using @api.
- Making Properties Reactive: Using @track.
- Connecting to Salesforce Data: Using @wire.
Common Decorators
1. @api
- Exposes properties or methods to parent components.
Example:
@api name; // Parent can set this property
2. @track
- Makes a property reactive, so UI updates automatically when the property changes.
Example:
@track message = 'Hello';
3. @wire
- Automatically fetches data from Salesforce (like Apex methods or wire adapters).
Example:
@wire(getContacts) contacts;
In Simple Words
Decorators in LWC add special behaviors to properties or methods, like sharing data, updating the UI, or fetching Salesforce data.
Explore the post below to explore more about 3 decorators in Salesforce LWC
- @api
- @track
- @wire
18. How do you bind events in LWC?
In LWC, you link events like – a button click from the HTML file to a Method in the JavaScript file.
Steps to Bind Events:
1. Define the Event in HTML:
- In the HTML file, use an event attribute like onclick, onchange, oninput, etc.
- Then specify the JavaScript method (for example: handleClick) to call in the same HTML file.
Example:
2. Create the Method in JavaScript:
- Define the same method (handleClick) in the component’s .js file.
Example:
export default class MyComponent extends LightningElement {
handleClick() {
console.log('Button clicked!');
}
}
3. Access Event Data (Optional):
- Use the event parameter to get details like the value of an input or the event type.
Example:
handleInput(event) {
console.log(event.target.value); // Logs the input's value
}
In Simple Words
- Use on[event] in HTML file to connect to a method in JavaScript file.
- Write the method in JavaScript to handle the event.
19. What is the purpose of template.querySelector in LWC?
The template.querySelector method in Lightning Web Components (LWC) is used to find and access a specific HTML element in the component’s template.
Purpose
- To interact with an element directly, like changing its value, style, or attributes.
- It selects the first matching element based on the provided CSS selector.
Example:
handleClick() {
const inputElement = this.template.querySelector('input');
inputElement.value = 'Updated Value'; // Changes the input's value
}
In Simple Words
template.querySelector helps you find an element in your component so you can work with it.
20. What is the difference between template.querySelector and template.querySelectorAll in LWC?
1. template.querySelector:
- Finds one element that matches the CSS selector.
- Returns the first matching element.
Example:
// javascript
const button = this.template.querySelector('button'); // Selects the first button
2. template.querySelectorAll:
- Finds all elements that match the CSS selector.
- Returns a NodeList (like an array) of matching elements.
Example:
const buttons = this.template.querySelectorAll('button'); // Selects all buttons
buttons.forEach(btn => btn.disabled = true); // Disables all buttons
In Simple Words
- Use querySelector for one element.
- Use querySelectorAll for multiple elements.