Lightning Web Components Basics
Lightning Web Components (LWC) is a modern programming model for building Salesforce user interfaces. Built on web standards including HTML, JavaScript, and CSS, LWC leverages native browser capabilities rather than relying on proprietary frameworks, resulting in better performance and easier devel… Lightning Web Components (LWC) is a modern programming model for building Salesforce user interfaces. Built on web standards including HTML, JavaScript, and CSS, LWC leverages native browser capabilities rather than relying on proprietary frameworks, resulting in better performance and easier development. **Core Structure:** Every LWC consists of an HTML template file, a JavaScript file, and optionally a CSS file and an XML configuration file. The component folder name must be camelCase and match across all files. For example, a component named 'myComponent' would have myComponent.html, myComponent.js, myComponent.css, and myComponent.js-meta.xml. **HTML Templates:** LWC uses standard HTML with special directives like `lwc:if`, `lwc:else`, `for:each`, and `iterator` for conditional rendering and list iteration. Data binding uses curly braces `{propertyName}` to display JavaScript properties in templates. **JavaScript:** Components extend `LightningElement` from the 'lwc' module. Key decorators include: - `@api` - Makes properties public, allowing parent-to-child communication - `@track` - Tracks private reactive properties (though primitive properties are reactive by default) - `@wire` - Connects components to Salesforce data using wire adapters **Lifecycle Hooks:** Important hooks include `constructor()`, `connectedCallback()` (when inserted into DOM), `renderedCallback()` (after rendering), and `disconnectedCallback()` (when removed from DOM). **Communication Patterns:** Parent-to-child communication uses `@api` properties. Child-to-parent uses custom events via `CustomEvent` and `dispatchEvent()`. Unrelated components communicate through Lightning Message Service (LMS) or pub-sub patterns. **Data Access:** LWC interacts with Salesforce data through Wire Service using Lightning Data Service (LDS) adapters like `getRecord`, `createRecord`, or by calling Apex methods with `@wire` or imperatively. **XML Configuration:** The `.js-meta.xml` file defines where the component can be placed (Lightning App Builder, Record Pages, etc.) and its API version. LWC promotes reusability, testability, and follows modern web development standards, making it Salesforce's recommended UI framework.
Lightning Web Components Basics – Comprehensive Guide for Salesforce Platform Developer 1
Introduction
Lightning Web Components (LWC) is one of the most important topics on the Salesforce Platform Developer 1 exam. As Salesforce continues to modernize its UI development framework, LWC has become the standard for building custom user interfaces on the Salesforce platform. Understanding LWC basics is essential not only for the exam but also for real-world Salesforce development.
Why Lightning Web Components Are Important
Lightning Web Components represent Salesforce's evolution toward leveraging modern web standards. Here is why they matter:
• Modern Web Standards: LWC is built on native web standards including Custom Elements, Shadow DOM, Templates, and ECMAScript modules. This means developers use standard JavaScript and HTML rather than proprietary frameworks.
• Performance: Because LWC leverages the browser's native capabilities rather than a custom JavaScript framework layer, components render faster and are more lightweight than their Aura counterparts.
• Reusability: LWC promotes component-based architecture, allowing developers to build small, reusable pieces of functionality that can be composed into larger applications.
• Coexistence with Aura: LWC can coexist with Aura components, meaning organizations can gradually migrate their UI layer without a complete rewrite.
• Industry Alignment: Skills learned in LWC development are transferable to other web development frameworks because they are based on web standards.
What Are Lightning Web Components?
A Lightning Web Component is a custom HTML element built using standard HTML, JavaScript, and CSS. Each LWC consists of a bundle of files that together define the component's structure, behavior, and styling.
Component Bundle Structure:
Every LWC lives inside a folder, and the folder name defines the component name. The bundle typically contains:
• HTML file (.html): Defines the component's template (markup). It uses a <template> tag as the root element.
• JavaScript file (.js): Contains the component's logic. The class extends LightningElement from the lwc module.
• CSS file (.css): Optional. Provides component-scoped styles using Shadow DOM encapsulation.
• Metadata configuration file (.js-meta.xml): Defines the component's metadata, including where it can be used (e.g., Lightning App Builder, Record Pages, Community Pages) and its API version.
• SVG file (.svg): Optional. Provides a custom icon for the component.
• Test files (__tests__ folder): Optional. Contains Jest test files for unit testing the component.
Naming Conventions:
Component folder names must be in camelCase (e.g., myComponent). When referenced in HTML markup, they use kebab-case with a namespace prefix (e.g., <c-my-component> where c is the default namespace).
How Lightning Web Components Work
1. Reactive Properties and Data Binding
LWC uses a reactive system. When a component's property changes, the framework automatically re-renders the affected portion of the template.
There are several types of properties:
• Public Properties (@api): These are exposed to parent components. A parent can set these values when including the child component. Decorated with @api.
• Tracked/Reactive Properties: In recent versions of LWC, all fields in a component class are reactive by default. If you assign a new value to a field, the component re-renders. Note: For objects and arrays, you must reassign the reference (not mutate in place) to trigger reactivity, unless you use @track (which enables deep reactivity for object properties and array elements).
• Private Properties: Fields without any decorator are private and reactive but not accessible from outside the component.
2. The @wire Decorator
The @wire decorator is used to read Salesforce data reactively. It connects a component to an Apex method or a Lightning Data Service (LDS) wire adapter.
Key wire adapters include:
• getRecord – retrieves a single record
• getListUi – retrieves list view data
• getObjectInfo – retrieves object metadata
• getPicklistValues – retrieves picklist values
Wire service results are provisioned reactively. When the parameters change, the wire adapter automatically re-fetches the data. The result object has data and error properties.
You can wire to a property or to a function:
• Wiring to a property: The framework assigns the result to the property automatically.
• Wiring to a function: The framework calls the function with the result, allowing you to process the data before storing it.
3. Calling Apex Methods
LWC can call Apex methods in two ways:
• Using @wire: Reactively calls the Apex method and caches the result. The Apex method must be annotated with @AuraEnabled(cacheable=true).
• Imperatively: Call the imported Apex method directly (returns a Promise). This is useful for DML operations where caching is not appropriate. The Apex method must be annotated with @AuraEnabled.
To import an Apex method:
import methodName from '@salesforce/apex/ClassName.methodName';
4. Component Lifecycle Hooks
LWC provides lifecycle hooks that let you execute logic at specific stages:
• constructor(): Called when the component is created. Must call super() first. Do not access child elements or set attributes here.
• connectedCallback(): Called when the component is inserted into the DOM. Use this for initialization logic, such as fetching data or subscribing to events. The component's template is not yet rendered at this point.
• renderedCallback(): Called after every render of the component. Use cautiously to avoid infinite rendering loops. Good for DOM manipulation after rendering.
• disconnectedCallback(): Called when the component is removed from the DOM. Use for cleanup such as removing event listeners or unsubscribing from channels.
• errorCallback(error, stack): Called when a descendant component throws an error. Used to create error boundaries.
5. Event Handling and Communication
LWC uses standard DOM events for communication:
• Parent to Child: Pass data via public properties (@api) or call public methods (@api decorated methods) on the child.
• Child to Parent: Dispatch custom events using new CustomEvent('eventname', { detail: data }). The parent handles it with an oneventname handler in the template.
• Unrelated Components: Use the Lightning Message Service (LMS) with @wire(MessageContext) and publish/subscribe methods, or use a pub-sub pattern. LMS is the preferred approach for communication across the DOM hierarchy.
Important event rules:
• Custom event names should be lowercase with no special characters (no underscores or uppercase letters).
• Events do not bubble out of Shadow DOM by default. Set bubbles: true and composed: true if needed (use sparingly).
6. Template Directives
LWC templates support several directives:
• lwc:if, lwc:elseif, lwc:else (modern syntax) or if:true / if:false (legacy syntax): Conditionally render DOM elements.
• for:each: Iterates over an array. Requires a key attribute on the direct child element for efficient DOM updates.
• iterator: Similar to for:each but provides additional properties like first, last, index, and value.
• lwc:dom="manual": Allows manual DOM manipulation within a container element (e.g., for inserting third-party library-rendered content).
7. Shadow DOM and Styling
LWC uses Shadow DOM for style encapsulation. This means:
• CSS defined in a component only applies to that component's markup.
• External styles do not leak into the component.
• You cannot use document.querySelector to reach into a component's shadow tree. Use this.template.querySelector instead.
8. Lightning Data Service (LDS)
LDS provides a way to perform CRUD operations without writing Apex:
• lightning-record-form: A form that handles both view and edit modes automatically.
• lightning-record-view-form: A read-only form.
• lightning-record-edit-form: An editable form with submit capabilities.
• Wire adapters like getRecord, createRecord, updateRecord, deleteRecord.
LDS manages a shared cache, so multiple components displaying the same record will stay in sync automatically.
9. Deploying and Using LWC
The .js-meta.xml configuration file controls where a component can be used. Key targets include:
• lightning__RecordPage – Record Pages
• lightning__AppPage – App Pages
• lightning__HomePage – Home Pages
• lightning__FlowScreen – Flow Screens
• lightning__RecordAction – Quick Actions
• lightningCommunity__Page – Experience Cloud Pages
You must set isExposed to true for the component to appear in Lightning App Builder.
10. Testing with Jest
Salesforce provides @salesforce/sfdx-lwc-jest for unit testing LWC. Jest tests run in a Node.js environment (not in a browser). They test component behavior in isolation by mocking wire adapters and Apex calls.
Key Concepts to Remember for the Exam
• LWC files must reside in the force-app/main/default/lwc/ directory in an SFDX project.
• Every LWC JavaScript class extends LightningElement.
• @api makes properties and methods public.
• @wire provisions data from wire adapters or cacheable Apex methods.
• @track enables deep reactivity for objects and arrays (though primitive fields are reactive by default without it).
• The component folder name is in camelCase; the HTML tag reference uses kebab-case with a namespace prefix.
• You cannot use id selectors reliably in LWC because the framework transforms IDs for uniqueness. Use classes or data-* attributes for querying elements.
• Base Lightning components (e.g., lightning-button, lightning-input, lightning-datatable) provide out-of-the-box functionality.
Exam Tips: Answering Questions on Lightning Web Components Basics
1. Know the file structure: Expect questions about which files are required (HTML and JS are required; CSS, SVG, and meta XML are technically optional but meta XML is needed for deployment). The folder name determines the component name.
2. Understand decorators thoroughly: The three decorators (@api, @track, @wire) are heavily tested. Know exactly when to use each one. Remember that @api is for public properties, @track is for deep object/array reactivity, and @wire is for reactive data provisioning.
3. Lifecycle hooks order: Know the order: constructor → connectedCallback → renderedCallback. Understand that disconnectedCallback fires on removal and errorCallback catches descendant errors.
4. Communication patterns: Questions often test parent-to-child (public properties/methods), child-to-parent (custom events), and unrelated component communication (Lightning Message Service). Know the correct pattern for each scenario.
5. Wire vs. Imperative Apex: Remember that @wire requires cacheable=true on the Apex method and cannot be used for DML. Imperative calls return Promises and are used when you need to perform DML or need more control over when the call executes.
6. Read questions carefully for Aura vs. LWC: Some questions may mix Aura and LWC concepts. For example, Aura uses <aura:attribute> and events with $A.get, while LWC uses decorators and standard DOM events. Do not confuse the two.
7. Naming conventions matter: If a question asks about referencing a component named myComponent in markup, the answer is <c-my-component>. The camelCase-to-kebab-case conversion is a common exam topic.
8. Shadow DOM implications: Understand that styles are scoped, and you must use this.template.querySelector (not document.querySelector) to access elements within the component.
9. Configuration file questions: Know the purpose of the .js-meta.xml file. Understand target configurations and that isExposed must be set to true for App Builder visibility.
10. Base components: Be familiar with common base components like lightning-record-form, lightning-record-edit-form, lightning-record-view-form, lightning-datatable, lightning-input, and lightning-button. Know when to use each one.
11. Eliminate wrong answers: When unsure, eliminate options that reference Aura-specific syntax, use incorrect decorator placement, or violate Shadow DOM rules. This strategy significantly improves your chances of selecting the correct answer.
12. Practice scenario-based thinking: The exam often presents a requirement and asks which approach is correct. For example, if a question asks how to display a record without Apex, think Lightning Data Service. If it asks how to pass data from child to parent, think custom events.
Summary
Lightning Web Components Basics is a foundational topic for the Platform Developer 1 exam. Focus on understanding the component bundle structure, decorators, lifecycle hooks, data binding, event communication patterns, and how LWC interacts with Salesforce data through wire adapters and Apex. Mastering these concepts will not only help you pass the exam but also prepare you for building modern, performant user interfaces on the Salesforce platform.
🎓 Unlock Premium Access
Salesforce Certified Platform Developer I + ALL Certifications
- 🎓 Access to ALL Certifications: Study for any certification on our platform with one subscription
- 2750 Superior-grade Salesforce Certified Platform Developer I practice questions
- Unlimited practice tests across all certifications
- Detailed explanations for every question
- PD1: 5 full exams plus all other certification exams
- 100% Satisfaction Guaranteed: Full refund if unsatisfied
- Risk-Free: 7-day free trial with all premium features!