Lightning Web Components (LWC) interview questions and answers
LWC interview questions test whether you can build Salesforce UI with Lightning Web Components the way the platform expects: a component bundle built on web standards, data loaded through Lightning Data Service or wired Apex, parents and children talking through public properties and events, and code that respects Shadow DOM and the platform's security layer. Expect decorator and lifecycle basics, a communication question across unrelated components, a wire versus imperative Apex comparison, and a debugging scenario such as a component that will not re-render.
By Evin JohnPublished 7 min read
Where LWC questions show up
LWC is the main topic in Salesforce developer, Salesforce front-end and many Salesforce consultant interviews. Admin-leaning roles touch it lightly. Developer loops usually include a concept round, a live exercise (build a small component or fix a broken one, sometimes in a scratch org or a shared editor), and a design talk about how a feature splits between Flow, Apex and components. For the data model, sharing, Flow and governor limits, see the broader Salesforce interview questions guide; this page stays on the component layer.
Fundamentals: the bundle, decorators and templates
| Question | What it tests | What a strong answer shows |
|---|---|---|
| What is Lightning Web Components built on? | Platform basics | Web standards: custom elements, ES modules, templates and Shadow DOM, with a thin Salesforce layer for data, security and base components. That is why it feels closer to plain JavaScript than Aura did. |
| Which files make up a component? | Bundle | An HTML template, a JavaScript class extending LightningElement, a .js-meta.xml configuration file and optionally CSS, tests and an SVG icon, all in a folder named after the component. |
A folder is called contactPicker. How do you use it in markup? | Naming | As <c-contact-picker>. Camel case becomes kebab case and c is the default namespace. |
| What does the meta XML file control? | Exposure | The API version, whether the component is exposed, and its targets (record page, app page, home page, Flow screen, Experience Builder), plus design attributes an admin can set in App Builder. |
| What do @api, @wire and @track do? | Decorators | @api makes a property or method public to the parent. @wire binds a property or function to a wire adapter. @track makes the framework watch changes inside an object or array; plain fields are already reactive when reassigned. |
Why did a change to this.filters.status not re-render? | Reactivity | Mutating a property inside a plain object field is not observed. Reassign a new object (this.filters = { ...this.filters, status }) or decorate the field with @track. |
| Can a child change a value passed in through @api? | Ownership | It should not. Public properties belong to the parent, and objects passed down are read-only. Copy the data or fire an event asking the parent to change it. |
| How do conditional rendering and lists work in templates? | Templates | Conditional directives (lwc:if, lwc:elseif, lwc:else in current code, if:true in older code) and for:each with a unique key on the first element of each item, or iterator when you need first and last flags. |
| Why can a template not call a function with arguments? | Template rules | Templates only bind to properties and getters, which keeps them declarative. Compute values in a getter, or pass data through data- attributes and read them from the event. |
| Name the lifecycle hooks in order. | Lifecycle | constructor, connectedCallback when inserted, renderedCallback after every render, disconnectedCallback when removed, and errorCallback in a parent when a descendant throws. |
Component communication
- How does a child tell its parent something happened? It dispatches a
CustomEventwith a lowercase name and a smalldetail. The parent listens with anonprefix in markup, for exampleoncontactselect. - What do `bubbles` and `composed` change? By default an event stops at the child's host.
bubbles: truelets it travel up the parent's tree, andcomposed: truelets it cross shadow boundaries. Use the narrowest setting that works, since composed events become part of your public API. - How does a parent call a method on a child? Decorate the child method with @api, give the child a reference in the template, and call it through
this.template.querySelector. Use this sparingly; properties are easier to reason about. - How do two components with no parent-child link communicate? Lightning Message Service, which publishes and subscribes on a message channel and works across LWC, Aura and Visualforce on the same page. The older pubsub module is a legacy pattern.
- Can an Aura component contain an LWC, and the other way round? Aura can contain LWC. LWC cannot contain Aura, which is why migrations usually start from the leaf components up.
Data: Lightning Data Service, wire and Apex
| Question | What it tests | What a strong answer shows |
|---|---|---|
When would you use lightning-record-form instead of writing your own form? | Using the platform | For straightforward create, view and edit of one record. It respects field-level security and page layouts and needs no Apex. Custom forms come in when layout or behavior is unusual. |
What does the $ in recordId: '$recordId' mean? | Reactive parameters | It makes the wire parameter reactive: when the property changes, the adapter fetches again. Without it the string is passed literally. |
| Wired Apex or imperative Apex? | Choosing | Wire suits reads that should cache and refresh with their parameters; the method must be marked cacheable, which forbids DML. Imperative calls suit writes, user-triggered actions and calls whose timing you control. |
Why is a property decorated with @wire undefined in connectedCallback? | Timing | Wire results arrive asynchronously and the value is an object with data and error. Read it in a getter or a wired function, and handle the loading state. |
| How do you refresh wired data after saving? | Cache | Call refreshApex on the wired result for Apex wires, or use the record notification APIs so Lightning Data Service reloads the record everywhere it is shown. |
| How do you import a field so a rename is caught at deploy time? | Schema imports | Import it from @salesforce/schema, for example Account.Name. The platform knows about the reference, so the field cannot be deleted while the component uses it. |
| What does a cacheable Apex method mean for security? | Security | Nothing extra by itself. The Apex class still needs with sharing and explicit object and field permission checks, because Apex runs in system context by default. |
| How would you show a success or error message? | UX | Dispatch a ShowToastEvent for user feedback, and reduce Apex or UI API errors into readable text instead of printing the raw body. |
import { LightningElement, api, wire } from "lwc";
import { getRecord, getFieldValue } from "lightning/uiRecordApi";
import searchContacts from "@salesforce/apex/ContactSearchController.search";
import ACCOUNT_NAME from "@salesforce/schema/Account.Name";
export default class ContactPicker extends LightningElement {
@api recordId; // supplied by the record page
results = [];
error;
timer;
@wire(getRecord, { recordId: "$recordId", fields: [ACCOUNT_NAME] })
account;
get accountName() {
return getFieldValue(this.account.data, ACCOUNT_NAME);
}
handleInput(event) {
const term = event.target.value;
clearTimeout(this.timer);
// eslint-disable-next-line @lwc/lwc/no-async-operation
this.timer = setTimeout(() => this.search(term), 300);
}
async search(term) {
if (!term || term.length < 2) {
this.results = [];
return;
}
try {
this.results = await searchContacts({ accountId: this.recordId, term });
this.error = undefined;
} catch (e) {
this.error = e?.body?.message ?? "Search failed";
}
}
handleSelect(event) {
const id = event.currentTarget.dataset.id;
this.dispatchEvent(new CustomEvent("contactselect", { detail: { id } }));
}
disconnectedCallback() {
clearTimeout(this.timer);
}
}<template>
<lightning-card title={accountName}>
<div class="slds-p-horizontal_small">
<lightning-input type="search" label="Search contacts" onchange={handleInput}></lightning-input>
<template lwc:if={error}>
<p class="slds-text-color_error">{error}</p>
</template>
<template for:each={results} for:item="contact">
<button key={contact.Id} data-id={contact.Id} class="slds-button" onclick={handleSelect}>
{contact.Name}
</button>
</template>
</div>
</lightning-card>
</template>- Why debounce the search? Each keystroke would otherwise call Apex, use server capacity and race older responses against newer ones. A short delay sends one request per pause in typing.
- Why is `recordId` not set in the constructor? Public properties are assigned after construction. Code that needs them belongs in
connectedCallback, a getter or a reactive wire. - What would you test in Jest for this component? That typing two letters calls the mocked Apex method once after the timer, that results render as buttons, that an Apex error shows the message, and that clicking fires
contactselectwith the right id.
Shadow DOM, styling and security
| Question | What a strong answer shows |
|---|---|
| Why does my CSS not reach the inside of a base component? | Shadow DOM encapsulates each component's styles. Use the documented styling hooks (CSS custom properties) or SLDS classes rather than reaching into internals, which can break on upgrade. |
Why does document.querySelector not find my element? | A component queries its own shadow tree through this.template.querySelector. Global document queries do not cross other components' boundaries. |
| Synthetic or native Shadow DOM, and what is light DOM? | On many Salesforce surfaces encapsulation has historically been emulated (synthetic shadow). Light DOM is an opt-in that renders without a shadow root, useful for third-party styling or global CSS, at the cost of encapsulation. |
| What do Lightning Locker and Lightning Web Security do? | Both isolate components from different namespaces so one cannot read another's DOM or globals. Lightning Web Security is the newer architecture and is friendlier to modern third-party libraries; which one an org runs depends on its settings. |
| How do you load a third-party chart library? | Upload it as a static resource and load it with loadScript and loadStyle in renderedCallback, guarded by a flag so it loads once. Check it works under the org's security layer and Content Security Policy. |
| Why did my component re-render forever? | renderedCallback changed a tracked property, which triggered another render. Guard the work with a flag or move it out of the hook. |
Senior and scenario questions
- A record page with eight custom components loads slowly. How do you investigate? Look at how many server calls fire on load, whether reads are cacheable, whether components fetch the same record separately instead of sharing Lightning Data Service, and whether heavy components can load on tab activation.
- A data table must show 50,000 rows. It should not render them all. Use server-side pagination or infinite loading in
lightning-datatable, selective SOQL with indexed filters, and a sensible default sort. - When would you put logic in Flow instead of a component? When admins need to change it and the UI is standard. Embed an LWC as a Flow screen component when one step needs custom interaction.
- How do you plan an Aura to LWC migration? Inventory components, migrate leaves first since Aura can host LWC, replace application events with Lightning Message Service, and keep behavior identical behind tests before changing anything visible.
- A component must call an external API. Call it from Apex through a Named Credential so endpoint and authentication stay in configuration. For server-to-server trust, a signed assertion flow is common; JWT interview questions covers how those tokens are built and verified.
- How do you ship components between orgs? Source-tracked projects with the Salesforce CLI, scratch or sandbox orgs for development, Jest in CI, and deployment through a pipeline or unlocked packages rather than change sets for anything substantial.
Fictional example
- Interviewer
- Our quote component shows line items and a total. When a user changes a quantity, the item updates but the total stays the same. Here is the code.
- Candidate
- The handler does
this.lines[index].quantity = value, and the total is a getter overthis.lines. Sincelinesis a plain field, mutating an element inside it is not observed, so nothing re-renders the getter. The child row looks right only because it holds its own copy of the value. I would replace the array immutably, mapping to a new array with the changed line, which also keeps the data flow clear. Decoratinglineswith @track would work too, but I prefer reassigning. I would add a Jest test that changes a quantity and checks the rendered total, so the bug cannot come back quietly.
How to prepare for LWC interview questions
- Build in a free developer orgOne record-page component that reads with Lightning Data Service, one that searches through Apex, and one parent that listens to a child's event.
- Break reactivity on purposeMutate an object inside a field, watch the UI stay stale, then fix it by reassignment. Interviewers love this bug.
- Wire up Lightning Message ServiceMake two unrelated components on one page talk through a message channel, then explain why events would not reach.
- Write Jest testsMock a wire adapter and an Apex import, flush promises, and assert on rendered output and dispatched events.
- Prepare one design storyA feature you split between Flow, Apex and components, and what you would change now.
Salesforce rounds mix spoken concepts with live fixes, which makes mock practice worth recording. Natively, an AI interview assistant for Mac and Windows, transcribes your practice session on the computer and can suggest answers live, so you can test yourself on decorators and wire timing until the explanations come out cleanly. Take a screenshot of a broken component during practice and it can read the code and suggest where reactivity or event wiring went wrong. With Pro or the free trial it can use the résumé and job description you add, and every transcript and note stays available for review.
Questions people ask
What LWC questions are asked in Salesforce developer interviews?
The component bundle and meta XML targets, @api, @wire and @track, reactivity, lifecycle hooks, parent-child events, Lightning Message Service, Lightning Data Service versus Apex, Shadow DOM styling, Jest tests and Aura migration.
What is the difference between wired and imperative Apex in LWC?
A wired call runs when its reactive parameters change and needs a cacheable method, so it cannot do DML. An imperative call runs when your code calls it and suits saves and user-triggered actions.
When do you still need @track in LWC?
Plain fields re-render when they are reassigned. @track is only needed when you mutate properties inside an object or array and want the template to notice; reassigning a new copy is often cleaner.
How do unrelated Lightning Web Components communicate?
Through Lightning Message Service: one component publishes on a message channel and others subscribe, even across LWC, Aura and Visualforce on the same page.
Where to go next
Practice with the same assistant you would use on a call: it listens, transcribes and suggests answers from your own resume and the job description.
Facts on this page were last checked on . Product details come from the Natively app itself; if something here is out of date, tell us at hello@heynatively.com.
