|

Salesforce Developer LWC Tutorial (2026): The Beginner’s Guide to LWCs

If you’ve ever tried to build a Salesforce page layout that’s “almost right,” you already know the moment when clicks, flows, and standard UI stop being enough. That’s where Lightning Web Components (LWCs) come in. They let you build custom user interface elements that feel like Salesforce, but behave the way your business actually needs.

This guide walks through what LWCs are, when to use them, how to create one, how the key files work, and how to fetch data with both Lightning Data Service and Apex. You’ll also see the basics of decorators, lifecycle hooks, debugging, and parent-child communication.

What Are Lightning Web Components (LWCs) and When to Use Them?

A Lightning Web Component is a custom UI element you build for Salesforce users. It can be something small and practical, or something complex and interactive. Either way, it’s code you control, which means the UI can match your exact requirements.

The key decision point is simple:

Use LWCs when Salesforce’s standard UI falls short for business needs.

Before you build an LWC, it’s smart to try what Salesforce already gives you:

  • Standard page layouts and Lightning App Builder components
  • Screen flows (even if they’re not your favorite tool)
  • Declarative options that solve the problem without custom code

But most real projects hit a wall. Different companies have different workflows, and custom UI becomes unavoidable.

Setting Up Your Environment to Create LWCs

You can’t create LWCs in the Developer Console. To build Lightning Web Components, you need an IDE that supports Salesforce development.

Two common options:

This walkthrough uses VS Code because it’s the most common entry point.

Create your first Lightning Web Component in VS Code

In VS Code:

  1. Open the command palette with Ctrl+Shift+P
  2. Select “Create Lightning Web Component”
  3. Enter a component name

Naming rules to remember:

  • The first letter must be lowercase
  • No special characters, except underscores

After creation, you’ll see the component folder with files generated for you, plus a test folder. Testing matters, even if it gets skipped a lot. If you want to build Jest tests for LWCs, this is a solid follow-up: Jest testing tutorial for Lightning Web Components

The Four Main LWC Files (What Each One Does)

Most of your work in an LWC happens across four files:

FilePurposeWhat you use it for
HTMLMarkupWhat gets shown to users
JavaScriptLogicData loading, clicks, actions
CSSStylesCustom styling when SLDS isn’t enough
XML (metadata)ConfigWhere the LWC can be used, what can be configured

HTML file: what the user sees

Your HTML template tells the browser what to render. Text, headings, inputs, buttons, images, tables, all of it starts here.

If you want a refresher on HTML basics: HTML beginner tutorial

CSS file: custom styling

CSS stands for Cascading Style Sheets. It controls the look of your component when you need custom styling beyond what the Salesforce Lightning Design System provides.

Sometimes SLDS utility classes cover everything you need, and you barely touch CSS. Other times, CSS becomes a big part of making the UI match expectations.

Helpful references:

One practical gotcha from the build process shown in the video: if you create a CSS file and leave it empty, deployment can complain. Adding a placeholder rule is enough to get past that while you build.

JavaScript file: logic and interaction

The JavaScript file is where the behavior lives:

  • What happens on load
  • What happens on button click
  • How you retrieve and prepare data for display
  • How you handle events and state

If your HTML is “what users see,” JavaScript is “why it works.”

XML metadata file: placement and configuration

The XML (metadata) file controls:

  1. Where Salesforce lets you place the component (record pages, home pages, Experience Cloud, etc.)
  2. Which properties are configurable when an admin drops the component onto a page

That’s how you end up with a right-side configuration panel in App Builder, full of fields and options.

How to Display an LWC in Salesforce (App Builder Setup)

Before your LWC can be dragged into Lightning App Builder, update the metadata.

Expose the component and set targets

In the XML file:

  • Set isExposed to true
  • Add a targets section, then specify where it can be placed

Example target used in the video: a Lightning record page.

If you skip this, you won’t be able to drag it onto the page.

Optional: give it a friendly label

If your component name looks ugly in App Builder, add a masterLabel in the XML so admins see a nicer name.

Add it to a record page

In Salesforce:

  1. Open a Lightning Record Page
  2. Click Edit Page
  3. Search for your component in the left panel
  4. Drag it onto the canvas
  5. Save and activate if needed

At this stage, your component might show up as empty space if you haven’t added any HTML yet.

Fix “Why didn’t my UI update?” (Browser caching setting)

When you’re actively building an LWC, Salesforce’s browser caching can make you think nothing’s working. You update the component, refresh, and still see the old version.

To reduce this during development (dev orgs and sandboxes only), go to:

Setup → Session Settings → Caching

Then uncheck:

Enable secure and persistent browser caching to improve performance

This helps you actually see changes as you build. It’s not something to casually toggle in production.

Building the UI: HTML Basics and the LWC Component Library

Start simple with basic HTML

A quick way to prove the component renders is to add a paragraph:

  • A <p> tag displays basic text.
  • An <h1> tag displays a header.

That’s enough to confirm the component is placed correctly and visible.

Use pre-built Lightning components whenever possible

LWC development gets easier when you use the standard components Salesforce already provides. Things like tabsets, inputs, buttons, and datatables don’t need you to write all the markup from scratch.

The official reference is the Lightning Web Component Library.

A few popular ones mentioned:

  • lightning-tabset (tabs)
  • lightning-carousel (carousel UI)
  • lightning-datatable (record table display)
  • lightning-file-upload (uploading files)
  • lightning-input (text input and more)

This is how you build UIs that look and feel like Salesforce without spending hours recreating standard controls.

Prioritize the component library when you want Salesforce-native UI.

JavaScript Fundamentals for Lightning Web Components

Variables (class properties)

When an LWC is created, Salesforce generates a JavaScript class for it.

Inside the class, you’ll usually define class properties (often called variables). JavaScript doesn’t use Apex-style typing, so you don’t declare String or Boolean. You assign a value, and the type is inferred.

A variable is just a container for data you want to reuse.

Methods (functions)

A method is a block of logic you can run by name. In LWCs, methods commonly run when:

  • A button is clicked
  • A value changes
  • The component loads

Data binding: display JS values in HTML

To display a JavaScript property in your HTML template, you wrap it in curly braces, like {headerText}.

That’s how you take something from your JavaScript and show it in the UI.

Getter methods (for computed values)

Sometimes you don’t want to show a raw variable. You want to show the result of a function. Getter methods help with this because their return values can be displayed in templates.

The Three LWC Decorators You’ll Use (and Why They Matter)

Decorators are special markers you put on properties or methods to tell the framework how they should behave.

@api: public properties and methods

@api makes a property or method publicly accessible to other components (usually parent-child communication).

Two extra perks on record pages:

  • @api recordId can automatically give you the current record’s Id
  • @api objectApiName can automatically give you the current object’s API name (like Account)

This only makes sense on record pages. A home page has no record Id.

@track: reactivity for complex types

@track has changed over time.

  • For simple values (strings, numbers, booleans), you typically don’t need @track anymore.
  • For complex values (objects, arrays, sets, maps), @track is used so UI updates correctly when the value changes.

@wire: reactive data fetching

@wire is used to retrieve data reactively, including with Lightning Data Service. It can also be used with Apex if the Apex method is cacheable.

Fetching Data Without Apex: Lightning Data Service with @wire

Lightning Data Service (often referred to casually as the UI Record API) lets you retrieve record data without writing Apex.

In the demo, the component retrieves running user info.

Running user ID

You can import the running user’s ID and store it in a property. That gives you a recordId you can use with LDS.

Import fields from schema

To retrieve specific fields, you import them from @salesforce/schema, then build an array of fields to request.

Wire getRecord with a reactive parameter

A wire adapter runs getRecord and stores the result in a property. When the recordId changes, it runs again.

A key part is the reactive $propertyName syntax. When you write $userId, changing userId triggers a refresh of the wired data.

Use getters with getFieldValue

The wired result is structured, so getters are used to pull out and return the field values. Those getters can then be displayed in HTML.

Changing the userId to prove reactivity

The demo adds a button that changes the stored userId, which triggers the wire adapter to re-run and show a different user’s first name and email.

Important warning from the demo: don’t hardcode IDs in real code. IDs differ between production and sandboxes, so hardcoding breaks deployments.

Fetching Data with Apex: Imperative Calls from an LWC

Sometimes you need Apex. The demo shows how to create an Apex controller and call it from an LWC.

Step 1: Create an Apex class with an AuraEnabled method

In VS Code:

  • Ctrl+Shift+P
  • “Create Apex Class”
  • Name it (example: demo_lwc_controller)

The method must be:

  • public
  • static
  • decorated with @AuraEnabled

If you want to use the method with @wire, you also need cacheable=true. The demo focuses on imperative calls, and points out that wired Apex needs the cacheable setting.

The sample method:

  • Accepts an account name parameter
  • Runs a SOQL query for matching Accounts (with a limit)
  • Returns a list of accounts
  • Uses try-catch and throws an AuraHandledException for easier error handling in the UI

If you want a deeper breakdown of handled exceptions: Exception handling tutorial for Salesforce development

Step 2: Import the Apex method into your LWC

You import Apex methods into JavaScript in a way that looks similar to other imports. Then you can call them from LWC methods.

Step 3: Call Apex imperatively (async behavior)

Imperative Apex calls are asynchronous by default. That means other code can run before the Apex call finishes.

Two common patterns shown:

  • Promise style with .then() and .catch()
  • async/await style, which many developers find easier to read

The demo stores the returned list in a property like accountRecords and logs the result.

Debugging tip: JSON.stringify

When you console log a list or object, the browser may show object object. Converting the result to a string with JSON.stringify(...) makes it readable in the console.

Debugging Lightning Web Components

Browser console (Chrome DevTools)

To debug:

  1. Right-click the page
  2. Choose Inspect
  3. Go to the Console tab

Console logging is a simple and common way to see what your code is doing.

If you want to get better with DevTools: Chrome DevTools tutorial

Enable LWC debug mode (so you can view source)

There’s also a Salesforce setting you can enable on your user:

  • User record → Advanced User Details
  • Enable “Debug mode for Lightning web components”

With debug mode enabled, you can find your component code under DevTools → Sources, then locate it under the modules folder (often modules/c/). From there you can set breakpoints and step through logic.

LWC Lifecycle Hooks (Quick Intro)

Lifecycle hooks are methods that run at specific moments during a component’s life, in a set order.

One of the most used is connectedCallback(). It runs when the component is inserted into the DOM, just before it renders for the user.

In the demo, connectedCallback() is used to call the Apex-backed getAccounts() method automatically, before the user clicks anything.

If you want a full walkthrough of lifecycle hooks: LWC lifecycle hooks tutorial

Parent-Child Communication in LWCs

Breaking UI into smaller components makes reuse easier. It also means components need to communicate.

Child to parent: custom events

In the child component:

  • Create a method that calls this.dispatchEvent(new CustomEvent(...))
  • Give the event a name (example: coolEvent)
  • Pass data in the detail object (example: message text, plus a second property)

Then in the child HTML, add a button that fires the method.

In the parent HTML:

  • Include the child component tag
  • Listen for the event with on<EventName> (example: oncoolEvent)
  • Call a parent handler method

In the parent JavaScript:

  • The handler receives the event object
  • You can read event.detail to access the values sent by the child

Parent to child: @api properties and methods

For parent-to-child communication, the child exposes things using @api.

Two patterns shown:

  • Public property: the parent passes a value into the child, and the child displays it
  • Public method: the parent calls a child method using a query selector

To call a child method from the parent:

  • Use this.template.querySelector('c-child-demo-lwc')
  • Then call the @api method on the returned element

Naming tip: dashes in component tags

If your component name uses capital letters, the HTML tag uses dashes. That mismatch trips people up early, so it’s good to know it’s expected behavior.

Helpful Resources from Coding With The Force

If you want to strengthen the underlying skills that power LWCs, these are the same resources referenced with the tutorial:

Conclusion

Lightning Web Components give you a clean way to build custom UI when Salesforce’s standard tools can’t get you there. In one component, you can handle layout (HTML), style (CSS), logic (JavaScript), configuration (XML), and data access (LDS or Apex). If you focus on decorators, data binding, and basic debugging early, everything else gets easier. The fastest path forward is to build one small, useful LWC and iterate from there.

DISCLAIMER: This blog post was generated by the AI tool RightBlogger using the video I created and posted myself on YouTube


Need help with your Salesforce Org?

If you need help with your Salesforce org, schedule an hour of consulting time with me! I’m one of only ~500 Salesforce Certified Technical Architect’s (CTA) worldwide and I’ve spent over 30,000 hours building Salesforce implementations over the last decade!

Schedule and hour of consulting with me here!


Do you want to be the next Salesforce Certified Technical Architect (CTA)?

If you need training to help you on your journey to complete your Salesforce CTA Board then why not sign up for the cheapest Salesforce CTA course out there, with someone who has training over a million Salesforce professionals worldwide! You can check out and enroll in the course below!

Sign up for the CTA course here!

Or if a course isn’t your thing, you can always sign up for an hour long CTA study session with me here:
Schedule 1-on-1 CTA Coaching Here!


Get Coding With The Force Merch!!

We now have a redbubble store setup so you can buy cool Coding With The Force merchandise! Please check it out! Every purchase goes to supporting the blog and YouTube channel.

Get Shirts Here!
Get Cups, Artwork, Coffee Cups, Bags, Masks and more here!


Check Out More Coding With The Force Stuff!

If you liked this post make sure to follow us on all our social media outlets to stay as up to date as possible with everything!

Youtube
Patreon
Github
Facebook
Twitter
Instagram


Salesforce Development Books I Recommend

Advanced Apex Programming
Salesforce Lightning Platform Enterprise Architecture
Mastering Salesforce DevOps

Good Non-SF Specific Development Books:

Clean Code
Clean Architecture

Similar Posts