Everything you need to know about properties in Lightning Web Components

LWC has three types of properties namely private, private tracked and public tracked property.

Everything you need to know about properties in Lightning Web Components

In any programming language we will need variables to hold data and in Lightning Web Components we call them properties.

There are three types of properties

  • Private properties
  • Private tracked properties
  • Public tracked properties

1. Private properties These are the ones we might need when we try to perform some business logic in the JavaScript class file. Let’s look at how to declare them.

import { LightningElement } from 'lwc';

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

It’s suggested that we don’t use private properties in the template file(we will be looking at why is that so, below).

2. Private tracked properties Tracked properties are special variables and when there is any change that is being made to them the whole template file re-renders. This is how we declare one

import { LightningElement, track } from 'lwc';

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

3. Public tracked property This is a little more liberal property than private tracked property. If a property is declared as a public tracked property then we can assign values to it by the parent component in the hierarchy also they are tracked, meaning, if any change is made to the value of the property the whole template re-renders. This is how a parent component can declare the 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 = '';
}