LWC Questions
1. What are Lightning Web Components (LWC)?
Answer: Lightning Web Components (LWC) is a modern framework for building reusable,
dynamic web components in Salesforce. It leverages the latest web standards, such as Web
Components, Shadow DOM, and ECMAScript 6+, to deliver a lightweight and performant
way to build components for the Salesforce platform. LWC is built on top of the browser's
native APIs, making it more efficient and easier to maintain compared to its predecessor,
Aura.
2. What are the key differences between Aura Components and Lightning Web
Components?
Answer:
• Performance: LWC is built on native web standards, making it faster and more
efficient than Aura Components.
• Programming Model: LWC uses modern JavaScript (ES6+) and does not rely on a
proprietary framework like Aura.
• Bundle Size: LWC components are lighter in size due to reduced abstraction layers
and reliance on native web standards.
• Shadow DOM: LWC uses the Shadow DOM to encapsulate the component's internal
structure, styles, and scripts, providing better isolation and avoiding style leaks.
• Lifecycle Hooks: LWC has a simpler lifecycle with fewer hooks, making it easier to
manage component states and behavior.
3. What are the main building blocks of LWC?
Answer: The main building blocks of LWC are:
• JavaScript File (.js): Defines the component's behavior and handles logic.
• HTML Template File (.html): Defines the component's structure and layout.
• CSS File (.css): Provides styling specific to the component.
• Meta Configuration File (.xml): Specifies component metadata, including visibility and
API details.
4. Explain Shadow DOM in LWC.
Answer: Shadow DOM is a web standard that encapsulates the internal structure of a web
component. It allows components to have their own isolated DOM trees, which are separate
from the main document DOM. This isolation ensures that the component's styles and
scripts do not affect or get affected by elements outside of it, preventing style leakage and
enhancing security. LWC uses Shadow DOM by default to encapsulate components,
providing better modularization and scoping.
5. What are decorators in LWC, and why are they used?
Answer: Decorators in LWC are special annotations in JavaScript used to enhance the
functionality of variables or functions. The three primary decorators in LWC are:
• @api: Used to mark a public property or method that can be accessed from the
parent component.
• @track: Used to make a private property reactive, meaning changes to this property
will trigger a re-render of the component.
• @wire: Used to connect a component to Salesforce data or to a function that
retrieves data.
6. What is the purpose of the @track decorator in LWC?
Answer: The @track decorator is used to mark a private property as reactive in an LWC
component. When a property is marked with @track, the framework automatically re-
renders the component when the value of the property changes. This is particularly useful
for ensuring the UI stays in sync with changes in the component's state.
7. Explain the concept of data binding in LWC.
Answer: Data binding in LWC refers to the synchronization between the UI and the
component's data model. LWC supports both one-way and two-way data binding:
• One-way binding: Data flows from the JavaScript controller to the HTML template,
keeping the UI updated with changes in the component's state.
• Two-way binding: In addition to one-way binding, changes in the UI (such as user
input) automatically update the corresponding property in the component's
JavaScript controller.
8. What are wire adapters in LWC?
Answer: Wire adapters are built-in utilities in LWC that provide data to a component. They
are used with the @wire decorator to connect a JavaScript property or function to Salesforce
data or a custom Apex method. Wire adapters handle data retrieval asynchronously and
automatically refresh the data when changes occur.
10. How do you communicate between two Lightning Web Components?
Answer: There are several ways to communicate between two LWC components:
• Parent to Child: Use public properties (@api) or methods to pass data or call
functions.
• Child to Parent: Dispatch custom events from the child component, which the parent
component can handle.
• Sibling Components: Use a common parent component to facilitate communication
or use the Lightning Message Service (LMS) for decoupled communication.
11. What is Lightning Message Service (LMS) in LWC?
Answer: Lightning Message Service (LMS) is a cross-component messaging service in
Salesforce that allows communication between components on the same Lightning page,
whether they are LWC, Aura components, or Visualforce pages. LMS provides a standardized
way to publish and subscribe to messages, enabling decoupled communication without
requiring direct references between components.
12. How do you handle errors in LWC?
Answer: Errors in LWC can be handled using:
• Try-catch blocks: For synchronous code and promise chains.
• Error-boundary components: Special components that catch errors during rendering,
lifecycle methods, or event handlers in a component's child tree.
• @wire Error Handling: Using the error state of wire adapters to handle data-fetching
errors gracefully.
13. What is the use of the connectedCallback() in LWC?
Answer: connectedCallback() is a lifecycle hook in LWC that is invoked when a component is
inserted into the DOM. It is commonly used for initializing state, subscribing to data or event
streams, and setting up initial data or configurations.
14. What is the difference between connectedCallback() and renderedCallback()?
Answer:
• connectedCallback(): Called when the component is added to the DOM. It is typically
used to initialize data or set up event listeners.
• renderedCallback(): Called after every render of the component. It is used to perform
actions that depend on the rendered state of the DOM, such as manipulating DOM
elements or performing operations that require the element to be visible.
15. What is a template in LWC?
Answer: A template in LWC is an HTML file that defines the structure of a component. It
contains HTML tags, data bindings, and directives that represent how the component should
be displayed in the UI. The template file can include expressions to bind data, conditional
rendering, loops, and event handlers.
16. Can you explain the usage of dynamic components in LWC?
Answer: Dynamic components in LWC are created when you need to instantiate
components dynamically based on certain conditions or data at runtime. This can be
achieved using the <template> directives such as if:true, for:each, or by dynamically
importing components using the import() syntax.
17. What are slots in LWC, and how are they used?
Answer: Slots in LWC are placeholders in a component's template where child content can
be passed from the parent component. They allow a parent component to insert custom
content into predefined locations in the child component's markup. LWC supports default
and named slots for flexible content placement.
18. Explain Lifecycle Hook in LWC
Lightning Web Components (LWC) have several lifecycle hooks that are invoked at specific
points in a component's life cycle. These hooks allow developers to perform specific actions,
such as initializing data, modifying the DOM, or cleaning up resources.
Here is an overview of the lifecycle hooks available in LWC, along with their explanations:
1. constructor()
• When it’s called: Invoked when a new component instance is created.
• Purpose: Used to initialize the component’s state and to perform setup work before
the component is inserted into the DOM.
• Key Points:
o Do not access the DOM or manipulate component properties that are not
initialized yet.
o Can be used to initialize private properties and set up event listeners.
constructor() {
super(); // Always call super() first.
this.message = 'Hello, World!';
}
2. connectedCallback()
• When it’s called: Invoked when the component is inserted into the DOM.
• Purpose: Used to fetch data, set up subscriptions, or perform any operation that
requires the component to be present in the DOM.
• Key Points:
o Ideal for initializing data, adding event listeners, or setting up timers.
o Runs only once when the component is attached to the DOM.
connectedCallback() {
this.fetchDataFromServer();
}
3. renderedCallback()
• When it’s called: Invoked after every render of the component.
• Purpose: Used to perform any operations that require the DOM to be fully
constructed or updated, such as interacting with or manipulating DOM elements.
• Key Points:
o Can be called multiple times during the component’s life, particularly if
reactive properties or state changes trigger re-renders.
o Avoid making changes to the state or properties that would cause additional
re-renders, as it may lead to an infinite loop.
renderedCallback() {
console.log('Component has been rendered or re-rendered');
}
4. disconnectedCallback()
• When it’s called: Invoked when the component is removed from the DOM.
• Purpose: Used for cleanup, such as removing event listeners, canceling network
requests, or clearing timers.
• Key Points:
o Important for preventing memory leaks by cleaning up resources allocated
during the component's lifecycle.
o Runs only once when the component is removed from the DOM.
disconnectedCallback() {
clearInterval(this.intervalId); // Example of clearing a timer
}
5. errorCallback(error, stack)
• When it’s called: Invoked when an error occurs in a child component.
• Purpose: Used to handle errors that occur during the rendering, event handling, or
asynchronous processes
19. What about connectedcallback, can it be called more than once?
The connectedCallback() in Lightning Web Components (LWC) is only called once during the
lifecycle of a component, specifically when the component is inserted into the DOM for the
first time.
Key Points about connectedCallback()
1. Called Only Once Per Component Instance:
o connectedCallback() is called a single time when the component is initially
attached to the DOM. It will not be invoked again unless the component is
removed from the DOM and then reinserted (e.g., through conditional
rendering or navigating away from and back to the same page).
2. Use for Initialization Tasks:
o This is the ideal place to perform initialization tasks that require the
component to be in the DOM, such as fetching data, adding event listeners, or
subscribing to a service.
3. Does Not React to State or Property Changes:
o Unlike renderedCallback(), connectedCallback() does not get triggered by
changes to the component's state or reactive properties. It is not called on re-
render; it strictly corresponds to the moment the component is inserted into
the DOM.
Example Scenario
If your component is removed and then re-added to the DOM (e.g., through conditional
rendering like <template if:true={isVisible}>), connectedCallback() will be called again for the
same component instance when it is reinserted.
connectedCallback() {
console.log('Component is inserted into the DOM');
this.initializeData(); // Perform initial data fetch or setup
}
Summary
connectedCallback() is called only once when the component is attached to the DOM and
will not be called again unless the component is removed and then reattached to the DOM.
For operations that need to be performed multiple times, use renderedCallback() instead.
20. Tell us about LDS in lWC
Lightning Data Service (LDS) is a powerful service provided by Salesforce for interacting with
Salesforce data in Lightning components, including both Aura components and Lightning
Web Components (LWC). LDS is similar to the standard controller in Visualforce, offering a
declarative way to read, write, and modify Salesforce records without the need for Apex
code or manual server requests.
Key Features of Lightning Data Service (LDS)
1. Declarative Data Access:
o LDS provides a simple, declarative way to access Salesforce data without
needing to write custom Apex or SOQL queries. You can use LDS to retrieve,
create, update, and delete records directly from your Lightning components.
2. Efficient Data Management:
o LDS automatically handles caching, data synchronization, and data
consistency for you. It improves performance by minimizing the number of
server requests and by sharing data across components that use the same
records. It also ensures that data stays up-to-date across all components in
the app.
3. Reduced Server Calls:
o LDS caches records on the client side, reducing the number of server calls
needed to fetch data. When multiple components request the same record,
LDS serves the cached record, reducing server load and improving application
performance.
4. Data Consistency:
o LDS automatically handles data consistency and synchronization across all
components. When one component updates a record, other components
using the same record are automatically updated with the new data, ensuring
consistency.
5. Error Handling:
o LDS simplifies error handling by providing built-in methods for handling errors
related to CRUD operations. Errors are standardized, which makes debugging
easier.
Common Uses of Lightning Data Service (LDS)
• Loading Records:
o Retrieve records with minimal code using the lightning-record-form, lightning-
record-view-form, or the getRecord wire adapter in LWC.
• Creating, Updating, and Deleting Records:
o Use LDS to perform CRUD operations declaratively without writing Apex code.
The lightning-record-edit-form or updateRecord methods can be used for this
purpose.
• Handling Record Changes:
o LDS ensures all components are notified of changes to records they are using.
If a record is updated in one component, LDS automatically synchronizes that
change across other components.
How to Use Lightning Data Service in LWC
In LWC, you use the LDS wire adapters and functions to perform CRUD operations. Below are
the common ways to use LDS:
1. Loading a Record:
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import ACCOUNT_NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountRecordComponent extends LightningElement {
@wire(getRecord, { recordId: '001XXXXXXXXXXXXXXX', fields: [ACCOUNT_NAME_FIELD] })
account;
}
2. Creating or Updating a Record:
You can use the createRecord or updateRecord function to create or update records.
import { LightningElement } from 'lwc';
import { createRecord } from 'lightning/uiRecordApi';
export default class CreateAccountComponent extends LightningElement {
handleCreateAccount() {
const fields = { 'Name': 'New Account' };
const recordInput = { apiName: 'Account', fields };
createRecord(recordInput)
.then(account => {
console.log('Account created: ', account.id);
})
.catch(error => {
console.error('Error creating account: ', error);
});
}
}
3. Deleting a Record:
Use the deleteRecord function to delete a Salesforce record.
import { LightningElement } from 'lwc';
import { deleteRecord } from 'lightning/uiRecordApi';
export default class DeleteRecordComponent extends LightningElement {
handleDeleteRecord() {
deleteRecord('001XXXXXXXXXXXXXXX')
.then(() => {
console.log('Record deleted');
})
.catch(error => {
console.error('Error deleting record: ', error);
});
}
}
Benefits of Using Lightning Data Service
• Simplified Development: No need for custom Apex controllers or server-side code.
• Automatic Caching and Data Synchronization: Improves performance and ensures
data consistency.
• Built-in Error Handling: Easier debugging and consistent error messages.
• Security: Enforces all security, sharing rules, and FLS (Field Level Security)
automatically.
Limitations of Lightning Data Service
• Record-Level Limits: LDS might not be suitable for operations that involve a large
number of records simultaneously.
• No Complex Business Logic: While LDS handles CRUD operations efficiently, for
complex business logic and custom processes, Apex might still be necessary.
• Single Record Handling: LDS is optimized for operations involving single records. Bulk
operations might still require Apex.