Chapter 1: LWC Tutorial – Basics

Chapter 1: LWC Tutorial – Basics

On February 1, 2024, Posted by , In LWC Tutorial, By , With Comments Off on Chapter 1: LWC Tutorial – Basics

What are Lightning Web Components?

Lightning Web Components (LWC) is a modern framework introduced by Salesforce for building lightweight, web-standard-based components. As a Salesforce developer, I find LWC to be a powerful tool for creating fast, efficient, and reusable user interfaces for Salesforce applications. It leverages core web standards like HTML, CSS, and JavaScript, making it easier for me to develop and maintain components.

LWC also provides a layer of specialized Salesforce services on top of the core stack, enabling seamless access to Salesforce data and features. This framework is designed to work alongside Aura components, allowing for a smooth transition and interoperability between the two. Overall, LWC enhances the performance and scalability of Salesforce applications, making it a valuable addition to my development toolkit.

Why Lightning Web Component(LWC)?

Choosing Lightning Web Components (LWC) for Salesforce development has significantly improved the way I build and deliver applications. The primary reason I lean towards LWC is its alignment with modern web standards, including HTML, CSS, and modern JavaScript. This ensures that the components I develop are lightweight, leading to faster page loads and a better user experience. LWC’s compatibility with the web standards also means that my skills are transferable and relevant across different web development platforms, not just Salesforce.

Furthermore, LWC simplifies the development process with its data binding and event handling capabilities, making it easier for me to create dynamic and interactive applications. The framework’s emphasis on encapsulation and reusability of components allows for cleaner code and more efficient development workflows. By leveraging LWC, I’m able to deliver high-performance applications that enhance user engagement and satisfaction.

What is the different between Aura and LWC?

As a Salesforce developer, I often work with both Aura and Lightning Web Components (LWC) frameworks. The key difference between the two lies in their architecture and performance. Aura is an older framework that provides a robust set of tools for building dynamic web applications on the Salesforce platform. It uses a component-based architecture and relies heavily on its own custom syntax and event-driven model.

On the other hand, LWC is a more modern framework that aligns closely with standard web technologies like HTML, CSS, and modern JavaScript. LWC leverages web components standards, making it lighter and faster than Aura. This results in improved performance and a more seamless user experience. Additionally, LWC’s compatibility with standard web technologies makes it easier for developers with a background in web development to transition into Salesforce development. Overall, while Aura is still used for building complex applications, LWC is increasingly becoming the preferred choice for new development projects due to its efficiency and modern approach.

What are the advantages of using LWC over Aura?

One of the main advantages of using Lightning Web Components (LWC) over Aura is performance. LWC is designed to be lightweight and fast, leveraging modern web standards like HTML, CSS, and ECMAScript 7. This results in faster page load times and a smoother user experience. Additionally, LWC’s alignment with standard web technologies makes it easier for developers with a background in web development to adopt and work with Salesforce applications.

The framework’s emphasis on encapsulation and reusability of components leads to cleaner, more maintainable code. Moreover, LWC provides better integration with other web standards-based tools and frameworks, enhancing the overall development process. Overall, LWC offers a more modern, efficient, and developer-friendly approach compared to Aura, making it a preferred choice for new Salesforce development projects.

How to start the LWC Journey?

Starting the journey with Lightning Web Components (LWC) begins with understanding the basics of web development, including HTML, CSS, and JavaScript. As a developer, I found it helpful to familiarize myself with these core technologies before diving into LWC. Salesforce provides comprehensive documentation and trailhead modules that offer guided learning paths for LWC. I started by setting up a Salesforce Developer Edition environment to practice building components and exploring the LWC framework. It’s also important to understand the Salesforce data model and how LWC interacts with Apex classes to fetch and manipulate data.

Engaging with the Salesforce developer community through forums and groups can provide valuable insights and support as you learn and grow. By taking a step-by-step approach and leveraging available resources, I successfully embarked on my LWC journey, enhancing my skills and understanding of Salesforce development.

How to start the LWC Journey?

Here are some recommended steps that might help in your LWC development journey!

  1. Install VS Code and set it up for Salesforce Development.
  2. Start with JavaScript Basics in trailhead.
  3. Follow SLDS Lightning Design System for more updates.
  4. Check the component library before starting the build, you can build components from scratch.
  5. Practice and complete this LWC trail mix on the trailhead.

We can create lightning components using two programming models:

  1. LWC
  2. Aura

LWC uses Web components standards and provides what over and above is required to perform well on browsers.

With time, web standards have evolved a lot and browser vendors have implemented them in form native browser APIs and considering LWC is built on code natively running on browsers makes it more lightweight and delivers exceptional performance as compared to AURA.

If you take a look at the below figure you will notice how in the LWC programming model almost everything is coming from native APIs implemented by browsers. While in the AURA programming model, we had to implement a lot of proprietary components, modules, etc to make the framework work.

The next question that comes to mind is what are web components exactly?

In simple words, web components are a suite of different features allowing you to create new custom HTML tags (custom elements) which can be re-used multiple times on any web page while making sure the functionality of each custom element is encapsulated from each other

There are 3 main pillars of Web components.

1. Custom Elements :

These are nothing but simply user-defined HTML elements which we can use on our HTML page as we would any other standard element.

In vanilla JS we can create a custom element of our own by  creating a class that extends HTMLElement and further defining it using CusomElements.define(‘component-name’, className);

While in the case of the LWC framework automatically takes care of it for us.

2. Shadow DOM: 

It helps us to encapsulate our component structure and style so that nothing leaks out to or seeps into/from the main DOM.

Salesforce created synthetic shadow DOM to implement this web API few browsers that don’t support native Shadow DOM.

3. Templates: 

It’s an HTML element for holding HTML which is not rendered automatically on load and rather is rendered when certain criteria are met.

Note: All the boilerplate code required in vanilla JS is avoided in LWC (framework takes care of it all)

Frequently Asked Questions on LWC

What are Lightning Web Components (LWC) and how do they differ from Aura components?

Lightning Web Components, or LWC, is a modern framework designed by Salesforce for creating fast and efficient web components. Unlike Aura components, which are based on a custom framework, LWC is built on standard web technologies like HTML, CSS, and modern JavaScript, making it more lightweight and performant. For example, to create a simple LWC, you would use HTML to define the structure, JavaScript for the functionality, and CSS for styling, similar to standard web development practices.

In LWC, you can use decorators like @api and @track to expose properties and track reactive changes, respectively. For instance, to create a reactive property, you would use:

import { LightningElement, track } from 'lwc';

export default class MyComponent extends LightningElement {
    @track count = 0;
}

This approach makes LWC more aligned with modern web standards, offering better performance and easier integration with other web technologies compared to Aura components.

How do you communicate between LWC components on a page?

Communicating between Lightning Web Components (LWC) on the same page involves using custom events for child-to-parent communication and public properties or methods for parent-to-child interaction. When a child component needs to send data to its parent, it dispatches a custom event. Here’s a quick example of how a child component can dispatch an event:

// Child component
import { LightningElement, api } from 'lwc';

export default class ChildComponent extends LightningElement {
    @api
    sendDataToParent() {
        const event = new CustomEvent('customdata', {
            detail: { key: 'value' }
        });
        this.dispatchEvent(event);
    }
}

Explain the lifecycle hooks in LWC and their use cases.

In Lightning Web Components (LWC), lifecycle hooks are special methods that allow you to execute code at specific stages of a component’s lifecycle. Here’s a brief overview of some key lifecycle hooks:

  • constructor() : This is the first hook called in the lifecycle. It’s used for initializing component variables and state. However, it’s important not to perform any DOM manipulation or fetch data from APIs here.
  • connectedCallback() : This hook is invoked when the component is inserted into the DOM. It’s a good place to perform initialization tasks that require access to the DOM or to fetch data from APIs.
  • renderedCallback() : Called after the component has rendered and the DOM is updated. It’s useful for performing tasks that require interaction with rendered content, such as applying JavaScript libraries to rendered elements.
  • disconnectedCallback() : Invoked when the component is removed from the DOM. It’s used for cleanup activities, like removing event listeners or freeing up resources.

Here’s a simple example of using connectedCallback to fetch data:

import { LightningElement, wire } from 'lwc';
import getData from '@salesforce/apex/MyController.getData';

export default class MyComponent extends LightningElement {
    @wire(getData)
    data;

    connectedCallback() {
        console.log('Component is connected to the DOM.');
    }
}

In this example, connectedCallback is used to log a message when the component is added to the DOM, and the @wire decorator is used to fetch data from an Apex controller.

How do you handle events in LWC?

Handling events in Lightning Web Components (LWC) involves capturing user interactions or system events and responding to them. You can handle events using event listeners in your component’s template or JavaScript.

In the template, you can use the onclick attribute (or other event attributes like onchange , onblur , etc.) to specify a handler method. Here’s an example of handling a button click event in the template:

<!-- myComponent.html --><template>    <button onclick={handleClick}>Click Me</button></template>

In the JavaScript file, you define the handleClick method to handle the event:

// myComponent.jsimport { LightningElement } from 'lwc';export default class MyComponent extends LightningElement {    handleClick(event) {        console.log('Button clicked');    }}

In this example, when the button is clicked, the handleClick method is called, and “Button clicked” is logged to the console. You can also access event details, such as the target element or event data, through the event parameter.

Describe how you can call an Apex method from a Lightning Web Component.

Calling an Apex method from a Lightning Web Component (LWC) involves importing the method and using the @wire decorator or imperative API to invoke it. Here’s a simple example:

First, import the Apex method:

import getContacts from '@salesforce/apex/ContactController.getContacts';

Then, use the @wire decorator to automatically call the method and wire the result to a property:

import { LightningElement, wire } from 'lwc';export default class ContactList extends LightningElement {    @wire(getContacts) contacts;}

In this example, getContacts is an Apex method that retrieves a list of contacts. The @wire decorator calls the method and assigns the result to the contacts property, which can then be used in the component’s template.

Alternatively, you can use the imperative API to call the Apex method:

import { LightningElement } from 'lwc';import getContacts from '@salesforce/apex/ContactController.getContacts';export default class ContactList extends LightningElement {    contacts;    connectedCallback() {        getContacts()            .then(result => {                this.contacts = result;            })            .catch(error => {                console.error(error);            });    }}

In this example, getContacts is called in the connectedCallback lifecycle hook, and the result is assigned to the contacts property. This approach provides more control over when and how the Apex method is called.

Comments are closed.