Comprehensive Guide To Properties In Lightning Web Components

About Properties in Lightning Web Components

In every programming language, the need for variables to store data is inevitable, and in Lightning Web Components, these variables are referred to as properties.

There are three types of properties:

  • Private properties: These are utilized when executing business logic in the JavaScript class file. Let’s explore how to declare them.
import { LightningElement } from 'lwc';

export default class HelloWorld extends LightningElement {
	//declare a property
	message = '';
}

It is recommended to avoid using private properties in the template file, and the reasons for this will be explained below.

  • Private Tracked Properties: Tracked properties are unique variables, and any modifications made to them trigger a complete re-rendering of the template file. Here is how you declare one:
import { LightningElement, track } from 'lwc';

export default class HelloWorld extends LightningElement {
	//declare a tracked private property
	@track message = '';
}

  • Public Tracked Property:
    This property is more flexible than a private tracked property. If a property is declared as a public tracked property, values can be assigned to it by the parent component in the hierarchy. Additionally, they are tracked, meaning that any changes made to the property’s value trigger a complete re-rendering of the entire template. Here is how a parent component can assign a value to the child component.
//parent.html
<template>
	<c-child message="HEY!!!"></c-child>
</template>
//child.js
import { LightningElement, api } from 'lwc';

export default class Child extends LightningElement {
	//declare a tracked private property
	@api message = '';
}