Sub topic 13
Getter pitfalls and best practices
This chapter assumes you can write a getter, bind it in a template with { }, and know that reassigning a field re-renders the component. It covers the mistakes that cause bugs or slow rendering, and the habits that avoid them.
When a getter runs
LWC calls a getter each time the template reads it during a render. A render happens when a field the template used last time changes. Your getter has no control over how often it runs, so write it as though it could run many times.
Pitfall 1: side effects
A getter should only read state and return a value. It should not assign fields, call APIs, or dispatch events. Changing state during a render can cause errors or repeated renders, and the result is hard to predict.
// Avoid: the getter changes state while rendering
get label() {
this.renderCount++;
return `Rendered ${this.renderCount} times`;
}Put changes in event handlers or lifecycle hooks such as connectedCallback. Keep the getter as a pure calculation:
get label() {
return `${this.items.length} items`;
}Pitfall 2: expensive work
Sorting, filtering, or searching a large array inside a getter repeats that work on every render, even when the data has not changed. A render caused by an unrelated field still re-runs the getter.
Compute the result once, when the data changes, and store it in a field. The getter then returns the stored value.
import { LightningElement } from 'lwc';
export default class SortedList extends LightningElement {
_rawItems = [];
sortedItems = [];
set rawItems(value) {
this._rawItems = value || [];
this.sortedItems = [...this._rawItems].sort((a, b) => a.name.localeCompare(b.name));
}
}Here the sort runs once per assignment, not once per render. Use this approach only when the work is costly. A cheap length check or string join does not need it.
Pitfall 3: getters cannot take arguments
The template cannot call {formatPrice(item.price)}. A getter has no parameters. When each list item needs its own computed value, prepare the data first, as you did with displayContacts:
get displayItems() {
return this.items.map((item) => ({
...item,
priceLabel: `$${item.price.toFixed(2)}`
}));
}The template then binds to {item.priceLabel}.
Pitfall 4: expecting updates from in-place changes
A getter re-runs only when a render happens. If it reads this.address.city and you change city in place, nothing triggers a render unless the field is decorated with @track. Reassigning the whole object avoids the problem:
moveToLyon() {
this.address = { ...this.address, city: 'Lyon' };
}Pitfall 5: decorating both accessors
When you pair a getter and setter on a public property, put @api on only one of them. Decorating both is a compile error.
Summary of practices
| Do | Avoid |
|---|---|
| Return a value computed from fields | Assigning fields or calling APIs in a getter |
| Keep getters short and cheap | Sorting or filtering large lists on every render |
| Prepare per-item values in a `map` | Trying to pass arguments from the template |
| Reassign objects to trigger updates | Relying on in-place changes without `@track` |
| Name getters for what they return, such as `hasItems` | Giving a getter the same name as a field |
Exercise
A component has @track data and a getter get visibleRows() { return this.rows.filter(r => r.active).sort(byName); } on a table with 20,000 rows. Typing in an unrelated search box makes the page lag. What is the likely cause, and how would you fix it?
Show answer
Each keystroke changes a field, which triggers a render. Every render re-runs visibleRows, so the 20,000-row filter and sort repeat even though rows did not change. Fix it by computing the filtered and sorted array once, in the rows setter or the handler that changes rows. Store it in a field such as visibleRows and bind the template to that field.
Exercise
Why is this getter a problem, and what should replace it? get nextId() { this.counter += 1; return this.counter; }
Show answer
It changes a field while the component is rendering, which is a side effect. It also returns a different value on each render, so the output is unstable. Increment the counter in an event handler or lifecycle hook, and let the getter only return this.counter.