Sub topic 13
Getter pitfalls and best practices
This chapter assumes you can write a Lightning Web Component with a template and a JavaScript class. It also assumes you know how {property} binding, reactive fields, and get accessors work, as covered earlier in this tutorial. Getters are easy to write, so they are easy to misuse. This chapter covers the mistakes that cause slow components, odd rendering behavior, and hard-to-trace errors.
When a getter actually runs
A getter is not a stored value. The engine calls it each time the template needs the value, and it does not cache the result. A render happens when a reactive field that the template read last time changes. Every getter the template binds to runs again during that render, even if its own inputs did not change.
Three rules follow from this:
- A getter may run many times, so it must be cheap.
- A getter runs in the middle of rendering, so it must not change state.
- A getter must return the same output for the same inputs, because the engine can call it at any time.
The sections below show what goes wrong when you break each rule.
Pitfall 1: side effects in a getter
A side effect is anything a getter does besides reading state and returning a value. Typical examples are assigning to a field, pushing to an array, or calling a method that does either.
// badCounter.js
import { LightningElement } from 'lwc';
export default class BadCounter extends LightningElement {
renderCount = 0;
get label() {
// Wrong: the getter changes a field while the template is rendering.
this.renderCount += 1;
return `Rendered ${this.renderCount} times`;
}
}The getter reads renderCount, so the template depends on it. It also writes renderCount, which asks for another render. Depending on the engine mode, you get a thrown error about mutating state during render, or a render loop. Either way the number does not mean what you intended.
Put state changes in event handlers, lifecycle hooks, or setters. Keep the getter as a pure read:
// goodCounter.js
import { LightningElement } from 'lwc';
export default class GoodCounter extends LightningElement {
clicks = 0;
handleClick() {
this.clicks += 1;
}
get label() {
return `Clicked ${this.clicks} times`;
}
}<!-- goodCounter.html -->
<template>
<lightning-button label="Click me" onclick={handleClick}></lightning-button>
<p>{label}</p>
</template>Pitfall 2: expensive work in a getter
Because getters re-run on every render, a getter that loops over a large array or builds a big structure repeats that work each time anything in the template changes. A user typing in an input can trigger a render per keystroke, and each render recomputes every getter.
If the result depends only on a few inputs, compute it when those inputs change and store it in a field. A setter is a natural place for this:
// orderReport.js
import { LightningElement, api } from 'lwc';
export default class OrderReport extends LightningElement {
_orders = [];
summary = { count: 0, total: 0 };
@api
get orders() {
return this._orders;
}
set orders(value) {
this._orders = Array.isArray(value) ? value : [];
this.summary = this.buildSummary(this._orders);
}
buildSummary(orders) {
return {
count: orders.length,
total: orders.reduce((sum, order) => sum + order.amount, 0)
};
}
}<!-- orderReport.html -->
<template>
<p>{summary.count} orders, total {summary.total}</p>
</template>The reduce runs once per assignment of orders, not once per render. The template reads summary.count and summary.total. Dotted property access is allowed in templates, but calls and operators are not.
Do not cache by default. A getter that returns this.items.length is cheap, and caching it adds a second field that can fall out of sync. Cache only when the work is measurable or the input changes rarely compared with how often the component renders.
Pitfall 3: getters cannot take arguments
A template can only bind to a property or getter name. It cannot call {label(contact)}. This matters inside for:each, where you want a value that depends on the current item. A getter cannot see the loop variable.
The fix is to compute the per-item values before rendering, usually with map, and bind to the result:
// taskList.js
import { LightningElement } from 'lwc';
export default class TaskList extends LightningElement {
tasks = [
{ id: 't1', title: 'Write report', dueDay: 3 },
{ id: 't2', title: 'Review pull request', dueDay: 12 }
];
today = 10;
get displayTasks() {
return this.tasks.map((task) => {
const isOverdue = task.dueDay < this.today;
return {
id: task.id,
title: task.title,
isOverdue,
rowClass: isOverdue ? 'slds-text-color_error' : 'slds-text-color_default'
};
});
}
}<!-- taskList.html -->
<template>
<ul>
<template for:each={displayTasks} for:item="task">
<li key={task.id} class={task.rowClass}>{task.title}</li>
</template>
</ul>
</template>Each row object carries exactly what the template needs. The template stays free of logic.
Pitfall 4: mutating the source data
Methods such as sort, reverse, and splice change an array in place. Calling them on a field inside a getter mutates your component's state every time the template renders:
// sortedList.js
import { LightningElement, api } from 'lwc';
export default class SortedList extends LightningElement {
@api names = ['Grace', 'Ada', 'Alan'];
get sortedNames() {
// Wrong: sort() reorders this.names itself.
// return this.names.sort();
// Right: copy first, then sort the copy.
return [...this.names].sort();
}
}There is a second reason to copy. A value passed in from a parent through @api is read-only inside the child. In-place methods on it throw an error. Values from wire adapters are read-only in the same way. Copying with spread or slice() works in every case.
Pitfall 5: depending on state the engine cannot see
Re-rendering is driven by reactive fields. A getter that reads other kinds of state returns stale output because nothing tells the engine to run it again. Common sources:
- A variable declared outside the class, or a property on
window. - The result of
this.template.querySelector(...). On the first render the DOM does not exist yet, so the query returnsnull. Later changes to the DOM do not trigger a render. - A property on an object you changed in place without
@track(see the earlier chapter on tracking).
Model the state you need as a field on the class and update that field when the outside value changes. The getter then reads the field.
Pitfall 6: assigning to a getter with no setter
A getter without a matching setter makes the property read-only. Class code runs in strict mode, so an assignment throws a TypeError:
// priceTag.js
import { LightningElement } from 'lwc';
export default class PriceTag extends LightningElement {
unitPrice = 2;
quantity = 5;
get total() {
return this.unitPrice * this.quantity;
}
resetTotal() {
// Throws TypeError: no setter is defined for total.
this.total = 0;
}
}Change the inputs (quantity, unitPrice) and let the getter follow. For a public property that needs both, define a getter and setter pair and put @api on only one of the two accessors.
Best practices
The pitfalls above reduce to a short checklist.
| Pitfall | What you see | Fix |
|---|---|---|
| Side effect in getter | Render loop or mutation error | Move the change to a handler, setter, or lifecycle hook |
| Heavy computation | Slow typing, laggy re-renders | Compute on input change and store in a field |
| Per-item logic in a loop | Cannot call a getter with the loop item | Prepare row objects with `map` |
| In-place `sort` or `reverse` | Data reorders unexpectedly, or a read-only error | Copy the array first |
| Non-reactive dependency | Stale display | Read a class field, not outside state |
| Assigning to a getter | `TypeError` | Change the inputs, or add a setter |
Further habits that keep getters predictable:
- Name boolean getters as questions, such as
isOverdue,hasItems, orcanSubmit. The template then reads like a sentence. - Keep each getter small and single-purpose. Build larger values by having one getter call another, such as
get canSubmit() { return this.hasName && !this.isSaving; }. - Build class strings from an array so spacing stays correct as you add conditions:
// card.js
import { LightningElement } from 'lwc';
export default class Card extends LightningElement {
isSelected = false;
isDisabled = false;
get cardClass() {
return [
'slds-card',
this.isSelected && 'slds-is-selected',
this.isDisabled && 'slds-is-disabled'
]
.filter(Boolean)
.join(' ');
}
}- Return a stable type. A getter that returns an array in one case and
undefinedin another forces the template to handle both. Return an empty array instead. - Use a stable, unique
idfrom your data forkey, not the array index. Include it in the objects your getter returns. - Guard against missing data. Public properties are
undefineduntil the parent sets them, so writethis.productName ? ... : 'fallback'or use optional chaining.
Exercise
A component has @api records passed from a parent, and a getter get sortedRecords() { return this.records.sort((a, b) => a.rank - b.rank); }. It throws an error. Explain why, and write the corrected getter.
Show answer
Values passed in through @api are read-only inside the child. sort changes the array in place, so it fails on the read-only value. Even on a writable array it would reorder the source data on every render. Copy first: get sortedRecords() { return [...this.records].sort((a, b) => a.rank - b.rank); }.
Exercise
A getter get visibleCount() { this.lastCount = this.items.length; return this.lastCount; } is bound in the template. What is wrong, and how do you fix it?
Show answer
The getter assigns to lastCount while the template is rendering, which is a side effect. It can cause a mutation error or an extra render. Remove the assignment and return the value directly: get visibleCount() { return this.items.length; }. If lastCount is needed elsewhere, set it in the handler or setter that changes items.
Exercise
A list shows contacts, and each row needs a CSS class that depends on whether that contact is active. Why can't a getter named rowClass do this, and what should you do instead?
Show answer
A getter cannot receive the loop item as an argument, so it cannot compute a value for each row. Prepare the data with map in a getter such as displayContacts, adding a rowClass property to each row object, and bind the row's class to {contact.rowClass} inside the loop.