Sub topic 1
Fields in a Lightning web component
A Lightning web component stores its state in class fields. This chapter covers where fields live, how a template reads them, and how they differ from getters and local variables. Later chapters build on this to explain rerendering, @track, and @api.
Prerequisites
This chapter assumes you know the following:
- Basic modern JavaScript: classes,
importandexport, and spread syntax. - Basic HTML templates.
- The three files of a Lightning web component: an HTML template, a JavaScript class, and a metadata file.
- The difference between a primitive value (a number, string, or boolean) and a reference to an object.
You do not need to know anything about decorators yet. They are introduced in later chapters.
The three parts of a component
A component is a folder with files that share the folder's name. A component named counter has this layout:
counter/
counter.html
counter.js
counter.js-meta.xmlEach file has one job:
| File | Job |
|---|---|
| `counter.html` | The template. It describes the markup and reads values from the class. |
| `counter.js` | The class. It holds fields, getters, and methods. |
| `counter.js-meta.xml` | The metadata. It says where the component can be used. |
The class and the template are tied together by name. The framework looks for a default-exported class in the JavaScript file and renders the template with the same base name. The template does not import the class, and the class does not import the template.
A minimal component
The class below declares one field, count, and one method, increment.
import { LightningElement } from 'lwc';
export default class Counter extends LightningElement {
count = 0;
increment() {
this.count += 1;
}
}Three points about this class:
- It extends
LightningElement, the base class imported fromlwc. Without it the framework does not treat the class as a component. - It is the default export. A component file has exactly one default export.
count = 0;is a class field declaration. It creates a property on each instance of the component, starting at0.
The template pairs with the class:
<template>
<lightning-button label="Add one" onclick={increment}></lightning-button>
<p>Count: {count}</p>
</template>The root of every template is a <template> element. Inside it:
{count}is a data binding. It reads thecountfield and prints it.onclick={increment}attaches theincrementmethod as the click handler. There are no quotes around the braces, and you do not writethis.in a template.
Clicking the button runs increment. The field changes, and the paragraph shows the new number. You wrote no code to update the DOM.
Finally, the metadata file. This one makes the component available on app pages:
<?xml version="1.0" encoding="UTF-8"?>
<LightningComponentBundle xmlns="http://soap.sforce.com/2006/04/metadata">
<apiVersion>62.0</apiVersion>
<isExposed>true</isExposed>
<targets>
<target>lightning__AppPage</target>
</targets>
</LightningComponentBundle>Examples in later chapters show only the JavaScript and HTML. A real bundle needs this file, too.
What a field is
A field is a variable declared directly in the class body, outside any method:
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
customerName = 'Ada';
itemCount = 3;
isPriority = false;
tags = ['gift', 'fragile'];
shipping = { method: 'ground', days: 5 };
notes;
}Some details:
- A field can hold any JavaScript value: a primitive, an object, an array, a function, or
undefined. - A field with no initializer, like
notes, starts asundefined. A template that reads it renders nothing, and the framework does not raise an error. - Fields have no
let,const, orvarkeyword. - Inside the class you read and write a field through
this, as inthis.itemCount. - By default a field is private to its component. A parent component cannot read or set it. Making a field public takes the
@apidecorator, which a later chapter covers.
Field names are ordinary JavaScript identifiers. Use camelCase, such as itemCount. Some teams prefix a private backing field with an underscore, such as _amount. That is only a convention, and the framework treats _amount like any other field.
How a template reads fields
A template expression is {name}, where name is a property of the component. The property can be a field or a getter. Two rules matter here.
First, an expression names a property and nothing more. You cannot compute inside the braces:
<template>
<!-- Not allowed: expressions with operators or function calls -->
<p>{itemCount + 1}</p>
<p>{customerName.toUpperCase()}</p>
</template>The template compiler rejects these. A property path such as {shipping.method} is allowed, because it only reads a property of an object.
Second, when a value must be derived, put the logic in the class, using a getter:
import { LightningElement } from 'lwc';
export default class OrderSummary extends LightningElement {
customerName = 'Ada';
itemCount = 3;
get heading() {
return `${this.customerName.toUpperCase()} (${this.itemCount + 1} with gift)`;
}
}<template>
<h2>{heading}</h2>
</template>A getter has no storage of its own. It runs each time the template reads it, and it computes its result from fields. Compare the two:
| Row | Field | Getter |
|---|---|---|
| Holds its own value | Yes | No, it computes one |
| Can be assigned to | Yes | Not without a matching setter |
| Typical use | State that changes | A value derived from state |
A good rule: keep the minimum state in fields, and derive everything else with getters. If you store itemCount and also a separate itemCountPlusOne field, you must update both together. A getter cannot fall out of sync.
Fields versus local variables
A beginner mistake is to treat a local variable like a field. They behave differently:
import { LightningElement } from 'lwc';
export default class Greeter extends LightningElement {
greeting = 'Hello';
changeGreeting() {
let greeting = 'Goodbye'; // a new local variable, not the field
console.log(greeting); // prints "Goodbye"
}
}The let greeting inside the method creates a separate variable that disappears when the method returns. The field this.greeting is untouched. The template still shows "Hello". To change the field you must write this.greeting = 'Goodbye'.
Forgetting this. is the most common cause of "my component doesn't update" in new code. A local variable is never visible to the template, and the framework does not watch it.
Where fields get their first values
You have three places to give a field a starting value.
- An initializer in the class body. This is the simplest, and it works for constants and plain data.
``javascript count = 0; ``
- The constructor. Use it rarely. If you write one, call
super()first. Do not read attributes or touch child elements, because the component is not yet attached to the page.
``javascript constructor() { super(); this.startedAt = Date.now(); } ``
- A lifecycle hook such as
connectedCallback. The framework calls this method when the component is inserted into the page. It is the usual place for setup that depends on the environment.
```javascript import { LightningElement } from 'lwc';
export default class Clock extends LightningElement { startedAt;
connectedCallback() { this.startedAt = new Date().toLocaleTimeString(); } } ```
Prefer an initializer when the value is known at write time. Prefer connectedCallback when the value comes from somewhere else, such as the current time or a call to the server.
Fields are instance state
Each instance of a component gets its own copy of every field. If you put two c-counter elements on one page, clicking one button does not change the other counter. This is true because each element is a separate instance of the class.
A field is not shared state. Do not use it to share data between components. Instead, a parent passes values to a child through public properties, and a child tells its parent about changes through events. Both topics come later in this tutorial and in related ones.
Fields are reactive
You may have noticed that the Counter example had no special code to refresh the paragraph. That works because class fields are reactive: when a component's field changes and the template uses that field, the framework rerenders the component.
This is the starting point for the rest of the tutorial, so the exact meaning of "changes" matters. For now, hold on to this simple model:
- Assigning a new value to a field, as in
this.count += 1, counts as a change. - A field the template never reads cannot affect what is on screen.
The next chapters examine what happens when the value is an object or an array, where the answer is less obvious. Reassigning such a field works the same way as with a number. Changing something inside the object does not always count as a change.
Common mistakes with fields
| Mistake | Symptom | Fix |
|---|---|---|
| Declaring `let count = 0;` inside the class body | A syntax error | Write `count = 0;` with no keyword |
| Writing `count` instead of `this.count` in a method | A reference error, or a local variable that shadows the field | Use `this.count` |
| Writing `{this.count}` in the template | The template fails to compile | Write `{count}` |
| Writing `{count + 1}` in the template | The template fails to compile | Add a getter and bind to it |
| Setting a field in the constructor before `super()` | An error that `this` is not available | Call `super()` first |
| Expecting a parent to read a private field | The parent sees `undefined` | Expose the value with `@api` |
Summary
- A component is a class, a template, and a metadata file that share a name.
- Fields are declared in the class body without a keyword and are read in code as
this.name. - Templates read properties with
{name}. They cannot compute values, so use getters for derived values. - Fields are private by default, they belong to one instance, and they are reactive.
Exercise
A developer writes this class and the template shows Total: 10. After clicking the button, the template still shows Total: 10, but the console prints 15. Find the bug and fix it.
export default class Cart extends LightningElement {
total = 10;
addFive() {
let total = this.total + 5;
console.log(total);
}
}
Show answer
The method declares a local variable named total with let. That variable is separate from the field and disappears when the method ends, so the field is never changed. The fix is to assign to the field with this.total = this.total + 5;, or this.total += 5;. The reassignment changes the field, and the template rerenders with Total: 15.
Exercise
A component has fields price = 20 and quantity = 3. The template needs to show the line total, price * quantity. Why can't you write {price * quantity} in the template, and what should you write instead?
Show answer
A template expression can only name a property, so operators and function calls are not allowed inside the braces. Add a getter to the class, such as get lineTotal() { return this.price * this.quantity; }, and bind it in the template with {lineTotal}. Because the getter reads the fields each time, it never falls out of sync with them.