LWC interview questions and answers
LWC rounds test both JavaScript fundamentals and Salesforce-specific patterns. This set covers the questions that come up most: decorators, data access, component communication and debugging.
On this page (13 sections)
LWC basicsHow components talk to each otherLifecycle and reactivityWorking with data: wire, Apex and LDSBuilding the user interfaceSecurity, testing and performanceLWC with Flow and other toolsLWC Interview TipsInterviewer Follow-Up PatternsReal Project Experience SignalsRelated LWC Interview QuestionsFrequently Asked Questions about LWC InterviewsRelated ResourcesNew to this topic? Learn Lightning Web Components step by step before you practise.
LWC (Lightning Web Components) is Salesforce's modern frontend framework, and LWC interview questions are now standard in developer interviews. These questions range from fundamental concepts like decorators and lifecycle hooks to advanced topics like Shadow DOM, Lightning Message Service, dynamic components, and Jest testing. Beginners and experienced developers alike will find that this guide covers what interviewers actually ask.
Questions in each topic go from beginner to advanced. Use On this page to jump to the topic you need.
LWC basics
01What is Lightning Web Components and why did Salesforce create it?
What is Lightning Web Components and why did Salesforce create it?
LWC is Salesforce's modern UI framework built on web standards: standard HTML, JavaScript, and CSS. Salesforce created it because the older Aura framework used a proprietary component model that was slower and harder to learn. LWC uses native browser capabilities like custom elements, shadow DOM, and modules. This means better performance, smaller bundle sizes, and easier hiring since developers with standard web skills can learn LWC quickly.
02What is the difference between LWC and Aura components?
What is the difference between LWC and Aura components?
What the interviewer is checking: Whether you know LWC is the default today and can name the rare cases where Aura is still needed.
Architecture: Aura uses a proprietary framework; LWC uses web standards. Performance: LWC is faster due to native browser rendering. Syntax: Aura uses XML-like markup with custom expressions; LWC uses standard HTML with JavaScript. Event model: Aura has application and component events; LWC uses standard DOM events. Interoperability: LWC can be used inside Aura but not vice versa. Development: LWC has a lower learning curve for web developers. New projects should always use LWC.
Common mistake: Talking about Aura as an equal choice for new work.
03Explain the three LWC decorators: @api, @track, and @wire.
Explain the three LWC decorators: @api, @track, and @wire.
What the interviewer is checking: Up-to-date knowledge: plain fields are already reactive, so @track is only for changes inside objects and arrays.
@api makes a property public: parent components can pass data to it, and changes trigger re-rendering. @track was used for reactive private properties but is now deprecated: all properties are reactive by default. @wire connects a property or function to a Salesforce data source (Apex method or Lightning Data Service). Wire is reactive: when its parameters change, it automatically re-fetches data. Understanding when to use @api vs @wire is fundamental for LWC development.
Common mistake: Saying every property needs @track to re-render.
04What is Lightning Data Service (LDS) and why should you use it?
What is Lightning Data Service (LDS) and why should you use it?
What the interviewer is checking: Whether you avoid unnecessary Apex: LDS gives caching, sharing and field-level security for free.
LDS is a client-side data caching framework in Salesforce. It provides wire adapters like getRecord, createRecord, updateRecord, deleteRecord that handle CRUD without Apex. Benefits: automatic caching and cache invalidation, built-in FLS and CRUD enforcement, no Apex code needed for simple operations, and shared cache across components (one component's update is instantly visible in others). Use LDS for standard record operations. Use Apex only for complex queries or business logic.
Common mistake: Writing an Apex method to read or save a single record that LDS could handle.
05What is the difference between constructor() and connectedCallback()?
What is the difference between constructor() and connectedCallback()?
The constructor runs when the component is created, before it is added to the page, so you can't read public properties or access child elements there. connectedCallback() runs when the component is inserted into the DOM, when @api properties are set.
Most setup work, such as loading data or subscribing to message channels, belongs in connectedCallback.
06What is the difference between lwc:if and if:true?
What is the difference between lwc:if and if:true?
lwc:if, lwc:elseif and lwc:else are the newer conditional directives. They are faster and support else branches. if:true and if:false still work but are no longer recommended.
<template lwc:if={isLoading}>Loading…</template>
<template lwc:elseif={hasError}>Something went wrong</template>
<template lwc:else>{content}</template>07Why does every item in a for:each loop need a key?
Why does every item in a for:each loop need a key?
The key lets the engine track which item is which when the list changes, so it updates only the rows that changed instead of re-rendering everything.
Use a stable unique value such as the record Id. Never use the array index, because it changes when items are added or removed.
08How do you get the current user's Id or a record's field in LWC?
How do you get the current user's Id or a record's field in LWC?
Import the user Id with import userId from '@salesforce/user/Id';. For a record's fields, wire getRecord with the fields you need and read them with getFieldValue.
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME from '@salesforce/schema/Account.Name';
@wire(getRecord, { recordId: '$recordId', fields: [NAME] }) account;
get name() { return getFieldValue(this.account.data, NAME); }How components talk to each other
09How does parent-child communication work in LWC?
How does parent-child communication work in LWC?
Parent to child: pass data through @api properties; <c-child name={parentValue}></c-child>. The child declares the property with @api decorator. Child to parent: dispatch custom events; this.dispatchEvent(new CustomEvent('selected', { detail: data })). The parent listens with an event handler: <c-child onselected={handleSelected}></c-child>. For sibling or unrelated component communication, use Lightning Message Service (LMS) for pub/sub messaging.
10What do bubbles and composed mean on a custom event?
What do bubbles and composed mean on a custom event?
bubbles: true lets the event travel up through parent elements. composed: true lets it cross shadow DOM boundaries into the parent component's template.
The default (both false) is usually best: the event reaches only the direct parent that listens on the child. Turn them on only when a component further up must react, because bubbling events become part of your component's public API.
11How do you call a method on a child component?
How do you call a method on a child component?
Mark the child method with @api, give the child an lwc:ref in the parent template, then call it:
// parent.html
<c-child lwc:ref="child"></c-child>
// parent.js
this.refs.child.reset();Use this for actions such as reset or refresh. For data, pass properties down instead.
12What is Lightning Message Service and when do you use it?
What is Lightning Message Service and when do you use it?
LMS enables communication between components anywhere on the page, even across different frameworks (LWC, Aura, Visualforce). Create a Message Channel in metadata. Publisher: import and publish messages. Subscriber: import and subscribe with a handler. Use it when components need to communicate but aren't in a parent-child relationship, for example, a filter component and a data display component on the same page. Always unsubscribe in disconnectedCallback() to prevent memory leaks.
13What are slots in LWC and how do you use them?
What are slots in LWC and how do you use them?
Slots let parent components inject content into child component templates. Default slot: <slot></slot> in the child accepts any content. Named slots: <slot name='header'></slot> accepts targeted content via <span slot='header'>Title</span>. Use slots for building reusable container components: cards, modals, layouts. The child component defines the structure, and the parent provides the content. This is the composition pattern: one of the most powerful patterns in LWC.
14What is the purpose of the lwc:ref directive?
What is the purpose of the lwc:ref directive?
lwc:ref provides a way to get a reference to a child element or component in the template, similar to React's ref. Usage: add lwc:ref='myElement' to an element, then access it in JavaScript with this.refs.myElement. This replaces the older this.template.querySelector() approach and is more reliable. Use it for direct DOM manipulation, focusing elements, or calling methods on child components. Available in newer LWC versions.
15What is the pub-sub pattern in LWC beyond LMS?
What is the pub-sub pattern in LWC beyond LMS?
Beyond Lightning Message Service, you can implement pub-sub with a shared JavaScript module that maintains subscribers. Create a pubsub.js utility with subscribe(), unsubscribe(), and publish() methods using a Map of event names to callback arrays. Components import and use this module. This is useful for communication within the same namespace without creating message channels. However, LMS is the official Salesforce recommendation for cross-component communication.
Lifecycle and reactivity
16What are lifecycle hooks in LWC and when do they fire?
What are lifecycle hooks in LWC and when do they fire?
constructor(): fires when component is created, before DOM exists. Use for initializing properties. connectedCallback(): fires when component is inserted into DOM. Use for fetching data, subscribing to events. renderedCallback(): fires after every render. Use carefully to avoid infinite loops (guard with a flag). disconnectedCallback(): fires when component is removed from DOM. Use for cleanup like unsubscribing from events. errorCallback(error, stack): catches errors from child components.
17How do you use getters and setters in LWC?
How do you use getters and setters in LWC?
Getters are computed properties defined with get keyword: get fullName() { return this.firstName + ' ' + this.lastName; }. They re-evaluate whenever reactive properties they depend on change. Use them for derived data instead of storing computed values. Setters intercept property changes: set recordId(value) { this._recordId = value; this.loadData(); }. Combine @api with a setter to react when a parent passes new data. Getters replace Aura's expression evaluation in templates.
18Why can renderedCallback cause an infinite loop?
Why can renderedCallback cause an infinite loop?
renderedCallback() runs after every render. If it changes a tracked property, that triggers another render, which calls renderedCallback again.
Guard one-time logic with a flag (if (this.initialised) return;) and avoid changing reactive properties there.
19Why do LWC developers use the spread operator, and when does it matter?
Why do LWC developers use the spread operator, and when does it matter?
What the interviewer is checking: Whether you understand LWC reactivity and the read-only nature of wired data.
LWC tracks changes by noticing when a property gets a new value. Changing an object or array in place, for example this.items.push(x), is not always seen, especially for data from @wire, which is read-only. The spread operator creates a new copy, so the change is detected:
this.items = [...this.items, newItem]; // add to an array
this.contact = { ...this.contact, Phone: value }; // change one fieldIt is also how you edit wired data safely: copy it first, then change the copy. For nested objects you need to copy each level you change, or use structuredClone.
Common mistake: Mutating wired data directly and getting "Cannot assign to read only property".
Working with data: wire, Apex and LDS
20When would you use lightning-record-edit-form instead of a custom form?
When would you use lightning-record-edit-form instead of a custom form?
lightning-record-edit-form builds an edit form with LDS: it respects field-level security, validation rules and field types, and saves without Apex. Use it for standard create and edit screens.
Build a custom form with Apex only when you need logic the base component can't do, such as saving several related records together.
21What is the Wire Service and how does it work?
What is the Wire Service and how does it work?
The Wire Service provisions data reactively. It can connect to: 1) Lightning Data Service adapters (getRecord, getObjectInfo) for standard CRUD without Apex, 2) Custom Apex methods decorated with @AuraEnabled(cacheable=true). Wire automatically re-fetches when reactive parameters change. Data comes as {data, error}: always handle both. Wire results are read-only and cached. For operations that modify data (create, update, delete), use imperative Apex calls instead of wire.
22How do you call Apex methods from LWC?
How do you call Apex methods from LWC?
Two approaches: 1) Wire, for read-only, cacheable data. Decorate Apex with @AuraEnabled(cacheable=true). Wire provisions data reactively. 2) Imperative, for DML operations or non-cacheable calls. Import the method and call it directly: getAccounts().then(result => ...).catch(error => ...). Use async/await for cleaner code. Always handle errors. Imperative calls give you control over timing; wire is automatic. Choose wire for data display, imperative for user actions.
23How do you refresh data from a wired Apex method after an update?
How do you refresh data from a wired Apex method after an update?
Store the full wired result, then pass it to refreshApex() after saving:
import { refreshApex } from '@salesforce/apex';
@wire(getContacts, { accountId: '$recordId' }) wiredResult;
async handleSave() {
await saveContacts({ rows: this.draft });
await refreshApex(this.wiredResult);
}For records changed outside LDS, call notifyRecordUpdateAvailable() so other components on the page also refresh.
24How do you update a record from LWC without Apex?
How do you update a record from LWC without Apex?
Use updateRecord from lightning/uiRecordApi with the record Id and the fields to change. It goes through LDS, so security is enforced and the cache updates other components.
import { updateRecord } from 'lightning/uiRecordApi';
await updateRecord({ fields: { Id: this.recordId, Status__c: 'Approved' } });25How do you handle forms in LWC?
How do you handle forms in LWC?
Three approaches:
- Lightning-record-form: simplest, auto-generates fields with built-in validation and submission.
- Lightning-record-edit-form with lightning-input-field; more control over layout while keeping standard validation.
- Custom forms with lightning-input: full control over UI and validation but requires manual Apex submission.
For most scenarios, use lightning-record-edit-form. Go custom only when you need non-standard UI or complex cross-field validation. Always validate inputs before submission.
Building the user interface
26How do you show a toast message in LWC?
How do you show a toast message in LWC?
Import ShowToastEvent from lightning/platformShowToastEvent and dispatch it with a title, message and variant (success, error, warning, info).
import { ShowToastEvent } from 'lightning/platformShowToastEvent';
this.dispatchEvent(new ShowToastEvent({ title: 'Saved', message: 'Record updated', variant: 'success' }));Toasts don't show in every container, for example some Experience Cloud pages, so check where the component runs.
27How do you support multiple languages in LWC?
How do you support multiple languages in LWC?
Use custom labels for text, imported with import greeting from '@salesforce/label/c.Greeting';, and translate them in Translation Workbench. Use base components such as lightning-formatted-number and lightning-formatted-date-time so numbers and dates follow the user's locale.
Never hard-code user-facing text in templates.
28What is lightning-record-picker and when do you use it?
What is lightning-record-picker and when do you use it?
What the interviewer is checking: Whether you know current base components instead of rebuilding them yourself.
lightning-record-picker is a standard base component that lets a user search for and pick a record of one object, like a lookup field, without you writing any Apex. You set object-api-name, can add a filter and choose which fields to show and search on. It returns the selected record Id in the change event.
Use it for custom forms that need a lookup. Older code used a custom search component calling Apex; the record picker replaces that with less code, built-in accessibility and the user's sharing applied automatically.
Common mistake: Writing a custom Apex lookup for a simple case the record picker already covers.
30How do you open a modal in LWC?
How do you open a modal in LWC?
Create a component that extends LightningModal and open it with MyModal.open({ size: 'small', ... }). The open call returns a promise that resolves with the value passed to this.close().
This replaces the old pattern of building modals by hand with SLDS markup and gives better accessibility.
31How do you implement file upload in LWC?
How do you implement file upload in LWC?
Use lightning-file-upload component for simple file uploads to Salesforce Files. Set record-id, accepted-formats, and handle onuploadfinished event. For custom upload with preview: use an HTML input type='file', read the file with FileReader, display a preview, then call a custom Apex method to process the content. For large files, consider chunked upload. Always validate file size and type on the client before uploading.
32What are LWC CSS best practices?
What are LWC CSS best practices?
- Use SLDS utility classes for consistency.
- CSS custom properties for themeable values.
- :host selector for component-level styles.
- Avoid !important; it breaks encapsulation intent.
- Use CSS variables to style child components from parents.
- Media queries for responsive design.
- Avoid deep nesting: keep selectors simple.
- Use SLDS design tokens for spacing, colors, and typography.
Remember: Shadow DOM scopes styles, so global CSS doesn't affect LWC components.
33How do you open records as tabs in a Lightning console app from an LWC?
How do you open records as tabs in a Lightning console app from an LWC?
What the interviewer is checking: Real console experience, which most Service Cloud projects need.
Use the Workspace API from lightning/platformWorkspaceApi. It lets a component open a record as a workspace tab or subtab, focus or close tabs, and set a tab's label and icon. For example, a service agent's case list can open each case as a subtab under the account. These methods only work inside a console app, so first check with the IsConsoleNavigation wire adapter from the same module, and fall back to NavigationMixin in standard apps.
Common mistake: Using NavigationMixin in a console and wondering why records replace the current tab instead of opening a subtab.
34How do you implement a datatable with inline editing in LWC?
How do you implement a datatable with inline editing in LWC?
Use lightning-datatable with columns definition including editable: true on desired columns. Handle the onsave event to collect draft values. Process changes: validate data, call Apex to update records, then refresh the datatable. Handle errors per-row by setting errors on the datatable. For large datasets, implement server-side pagination. Key considerations: validate data before saving, handle partial failures gracefully, and provide clear error messages for each row.
35How do you create a component dynamically at runtime?
How do you create a component dynamically at runtime?
What the interviewer is checking: Performance thinking at a senior level: loading only what the user needs.
Use dynamic components: import the component class at run time and render it with lwc:is:
// JS
async connectedCallback() {
const ctor = await import('c/chartPanel');
this.panelCtor = ctor.default;
}
<!-- HTML -->
<lwc:component lwc:is={panelCtor}></lwc:component>This keeps the first load small, because rarely used parts are only downloaded when needed. It also lets one container show different components based on configuration, for example a dashboard whose widgets come from custom metadata. It needs Lightning Web Security enabled in the org and the lightning__dynamicComponent capability in the container's metadata file.
Use it sparingly: static imports are easier to analyse and package.
Common mistake: Putting every possible child in the template behind if:true, which still downloads all of them.
36Explain Shadow DOM in LWC.
Explain Shadow DOM in LWC.
LWC uses Shadow DOM to encapsulate component markup and styles. Each component's CSS is scoped: styles don't leak in or out. This prevents styling conflicts between components. However, it means you can't style child components from a parent using CSS. For shared styling, use CSS custom properties (CSS variables) or the SLDS design token system. LWC uses 'synthetic shadow DOM' by default, which provides encapsulation with some flexibility. Understanding this is key for debugging CSS issues.
37What are light DOM components?
What are light DOM components?
By default, LWCs use shadow DOM, which isolates their styles and markup. A component with light DOM (static renderMode = 'light') renders without a shadow root, so global styles and third-party libraries can reach it.
It is useful on Experience Cloud LWR sites for theming and SEO, but you lose style isolation, so use it on purpose.
Security, testing and performance
38How do you write Jest tests for LWC?
How do you write Jest tests for LWC?
Use the @salesforce/sfdx-lwc-jest package. Create the component in the test, mock Apex and wire adapters, change inputs, then check the DOM after await Promise.resolve().
Jest tests run locally, outside Salesforce, so they are fast and fit well in a CI pipeline.
39How do you use a third-party JavaScript library in LWC?
How do you use a third-party JavaScript library in LWC?
Upload it as a static resource, then load it with loadScript (and loadStyle for CSS) from lightning/platformResourceLoader, usually in renderedCallback with a guard so it loads once.
Check that the library works under Lightning Web Security and doesn't rely on accessing the global DOM.
40What are the most common LWC mistakes you see in code reviews?
What are the most common LWC mistakes you see in code reviews?
Calling Apex where LDS would do, missing key in loops, mutating @api properties inside the child, heavy logic in renderedCallback, not handling the error branch of wired calls, and not unsubscribing in disconnectedCallback.
Naming two or three of these with how you fixed them is a strong experienced-level answer.
41What is Lightning Web Security?
What is Lightning Web Security?
Lightning Web Security (LWS) is the security architecture that isolates components from different namespaces, replacing Lightning Locker. It allows more standard JavaScript and third-party libraries to work than Locker did.
Interviewers ask about it to see if you know why some libraries failed under Locker and work now.
42How do you handle error handling in LWC?
How do you handle error handling in LWC?
Multiple layers:
- Wire: check the error property: if (this.error) { // handle }.
- Imperative Apex: use .catch() or try/catch with async/await.
- UI feedback: use lightning-toast for notifications, inline error messages for form validation.
- ErrorCallback() lifecycle hook: catches errors from child components.
Best practice: create a reusable error handling utility that formats different error types (Apex, wire, network) into user-friendly messages. Log errors for debugging but show clean messages to users.
43How do you test LWC components?
How do you test LWC components?
Use Jest with @salesforce/sfdx-lwc-jest. Test types:
- Unit tests: test component logic, event handling, and rendering in isolation.
- Mock wire adapters: simulate data responses.
- DOM assertions: verify rendered HTML using querySelector.
Best practices: test behavior not implementation, mock all Apex and wire calls, test both success and error states, test accessibility. Run tests locally with 'npm test'. Tests don't count toward Apex coverage but are essential for quality.
44How do you optimize LWC performance?
How do you optimize LWC performance?
Key strategies:
- Minimize wire calls: use getRecord with specific fields, not layouts.
- Use lazy loading for components not immediately visible.
- Debounce search inputs.
- Use pagination for large datasets.
- Avoid unnecessary re-renders: use getters wisely.
- Cache Apex results where appropriate.
- Use requestAnimationFrame for DOM manipulations.
- Profile with Chrome DevTools.
- Use track only for objects/arrays that need deep reactivity.
- Minimize DOM nodes.
45How do you handle authentication state in LWC for communities?
How do you handle authentication state in LWC for communities?
In Experience Cloud (communities), use @salesforce/user/isGuest to check if the user is authenticated. Conditionally render UI based on auth state. For login redirects, use NavigationMixin with LoginPage reference. Handle session timeouts by catching 401 errors in Apex calls. For SSO, configure the community login page. Remember that wire adapters respect the guest user's permissions: design your Apex to handle both authenticated and guest contexts.
LWC with Flow and other tools
46How do you make a component available in Flow screens?
How do you make a component available in Flow screens?
Add the lightning__FlowScreen target in the component's configuration file and expose properties with @api. Use FlowAttributeChangeEvent to send values back to the Flow and FlowNavigationNextEvent to move to the next screen.
This is a popular question because it connects LWC and Flow skills.
47What is a scenario where LWC is better than Flow for UI?
What is a scenario where LWC is better than Flow for UI?
Use LWC when you need: complex UI interactions (drag and drop, real-time search), custom data visualization (charts, maps), integration with external JavaScript libraries, highly dynamic forms with conditional logic beyond what Flow screens support, performance-critical interfaces with large datasets, or pixel-perfect UI that matches specific design mockups. Flow screens are great for guided step-by-step processes. LWC is better for interactive, data-rich interfaces.
LWC Interview Tips
Know the difference between wire and imperative. This is asked in almost every LWC interview. Explain clearly when you'd use each approach.
Understand Shadow DOM. CSS scoping issues are a common interview topic. Explain how styles are encapsulated and how to share styles across components.
Practice building components. Interviewers may ask you to describe how you'd build a specific component. Think through data flow, events, and composition.
Know LDS well. Lightning Data Service eliminates the need for Apex in many cases. Show that you use the simplest solution available.
Interviewer Follow-Up Patterns
LWC interviews go deep into reactivity and lifecycle. The follow-up questions almost always test whether you understand how the framework actually works under the hood:
- You mention
@wire→ "how do you refresh wired data after an imperative update?" (answer:refreshApex). - You bring up events → "custom event vs Lightning Message Service: when which?"
- You explain reactivity → "why isn't my array update re-rendering?" (answer: shallow tracking).
- You mention
connectedCallback→ expect questions on renderedCallback infinite loops. - You answer about Apex calls → they push on cacheable=true and stale data.
Real Project Experience Signals
"On a customer portal we hit slow first-paint: moving heavy queries from @wire to imperative calls inside connectedCallback with skeleton loaders cut perceived load by half."
"We had a parent-child component tree that was re-rendering on every keystroke: switching to publish/subscribe via LMS solved it in under a day."
"For a Service Cloud console we used lightning/uiRecordApi instead of Apex wherever possible: fewer cache misses, no governor risk."
Strengthen your preparation by exploring related question banks in the same topic cluster. Each guide covers a unique angle of lwc interviews: pick the one closest to the role you are targeting.
Frequently Asked Questions about LWC Interviews
What is the most important LWC concept to know for interviews?
The reactivity model: specifically the difference between @api, @track, and @wire decorators, and how Lightning Data Service caches records. Closely behind: the component lifecycle (constructor, connectedCallback, renderedCallback, disconnectedCallback), event propagation rules, and Shadow DOM CSS encapsulation.
How do I prepare for LWC scenario-based questions?
Practice building small components end-to-end: parent-child communication with custom events and @api methods, sibling communication via Lightning Message Service, error handling for wired data, and infinite-scroll or lazy-loading patterns. Be ready to whiteboard component composition without an IDE.
When should I use @wire vs imperative Apex in LWC?
Use @wire for read operations that benefit from caching and automatic re-execution when reactive parameters change; it's the preferred pattern. Use imperative Apex for write operations (DML), one-off actions triggered by user clicks, or when you need fine-grained control over loading states and error handling.
Are Aura components still asked in LWC interviews?
Yes, but in a comparative way. Expect questions like 'why did Salesforce move from Aura to LWC' (web-standards alignment, performance, smaller framework footprint), and 'how do you migrate an Aura component to LWC.' Pure Aura coding questions are rare in 2026 interviews.
Do I need to know Jest testing for LWC interviews?
For mid-to-senior roles, yes. Be ready to explain the @salesforce/sfdx-lwc-jest setup, how to mock @wire adapters with createMockedAdapter, how to test event dispatching with addEventListener, and the difference between describe/it/test blocks. Coverage targets are looser than Apex but quality matters.