Sub topic 16
Performance and caching
This chapter assumes you can already build a component that loads data from Apex with @wire, as in the earlier chapters on data access and Apex controllers. You should also know how the maxRows property reaches the component from Experience Builder. Here you will learn where a site component spends its time and which caches you can rely on. You will also learn how to avoid work that no one sees.
Where the time goes
A site page feels slow for one of four reasons:
- The browser downloads too much code, styling, or imagery.
- The page makes too many server calls.
- Each server call does too much work.
- The component re-renders or re-fetches more often than needed.
For an Apex-backed component, the second and third reasons usually matter most. Guest visitors often arrive with a cold browser cache, so the first load matters more on a public site than inside a logged-in org.
The diagram shows what happens when a component wires a cacheable Apex method.
Cacheable Apex and the client cache
Marking an Apex method @AuraEnabled(cacheable=true) lets the platform store its result in the browser. When a wire adapter calls the method again with the same parameters, the platform can return the stored result instead of making a round trip.
A cacheable method has two rules:
- It must not perform DML or any other write.
- It must return the same result for the same inputs, as far as the user can tell.
If you break the second rule, users see stale data. For example, a method that returns "records created in the last five minutes" depends on the clock, not on its inputs. Make that method non-cacheable and call it imperatively.
| Situation | Choice | Reason |
|---|---|---|
| Read data that changes rarely | `cacheable=true` with `@wire` | Repeat requests skip the server |
| Read data that depends on the current time | `cacheable=false`, imperative call | A cached copy would be wrong |
| Create, update, or delete | `cacheable=false`, imperative call | Cacheable methods cannot do DML |
| Read a single record by Id | `getRecord` from `lightning/uiRecordApi` | Uses the shared Lightning Data Service cache |
The last row deserves attention. Lightning Data Service keeps one cache entry per record and shares it across components. If three components on a page show fields from the same record, getRecord can serve all three from one request. Three separate Apex calls cannot do that. Use Apex when you need joins, filters, or aggregates that the UI API does not offer.
A search component with caching, debounce, and refresh
The next example extends the CaseList component from earlier chapters. It adds a search box, bounds the server work, and gives the user a way to bypass the cache.
Start with the Apex class. It clamps maxRows so a page editor value or a tampered request cannot ask for thousands of rows.
public with sharing class CaseListController {
private static final Integer MAX_ALLOWED = 50;
@AuraEnabled(cacheable=true)
public static List<Case> searchCases(String searchTerm, Integer maxRows) {
Integer requested = (maxRows == null) ? 5 : maxRows;
Integer safeRows = Math.min(Math.max(requested, 1), MAX_ALLOWED);
String pattern = '%' + (searchTerm == null ? '' : searchTerm) + '%';
return [
SELECT Id, CaseNumber, Subject, Status
FROM Case
WHERE Subject LIKE :pattern
WITH USER_MODE
ORDER BY CreatedDate DESC
LIMIT :safeRows
];
}
}The query selects four fields rather than every field on Case. It filters in SOQL instead of in JavaScript, so the server returns only the rows the page shows. The bind variable :pattern also avoids SOQL injection.
Now the component class.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import searchCases from '@salesforce/apex/CaseListController.searchCases';
const DEBOUNCE_MS = 300;
export default class CaseSearch extends LightningElement {
@api maxRows = 5;
searchTerm = '';
rows = [];
error;
wiredResult;
timerId;
@wire(searchCases, { searchTerm: '$searchTerm', maxRows: '$maxRows' })
wiredCases(result) {
this.wiredResult = result;
const { data, error } = result;
if (data) {
this.rows = data;
this.error = undefined;
} else if (error) {
this.rows = [];
this.error = error;
}
}
handleSearchChange(event) {
const value = event.target.value;
window.clearTimeout(this.timerId);
this.timerId = window.setTimeout(() => {
this.searchTerm = value;
}, DEBOUNCE_MS);
}
handleRefresh() {
return refreshApex(this.wiredResult);
}
disconnectedCallback() {
window.clearTimeout(this.timerId);
}
}<template>
<lightning-input
type="search"
label="Search subject"
onchange={handleSearchChange}
></lightning-input>
<lightning-button label="Refresh" onclick={handleRefresh}></lightning-button>
<template lwc:if={error}>
<p>Cases could not be loaded. Try again later.</p>
</template>
<template lwc:else>
<ul>
<template for:each={rows} for:item="c">
<li key={c.Id}>{c.CaseNumber}: {c.Subject}</li>
</template>
</ul>
</template>
</template>Three details in this component matter for performance:
- Debounce. The wire re-runs whenever
searchTermchanges. Without the 300 ms timer, typing "refund" would trigger six calls. With it, the wire usually runs once, after the visitor pauses. - Reactive parameters. The
'$searchTerm'and'$maxRows'strings make the wire reprovision when those values change. Each distinct combination gets its own cache entry, so going back to an earlier search can return a stored result. refreshApex. It takes the whole object the wire delivered, not thedatafield. That is why the handler storesresultinwiredResult. If you passthis.rowsinstead, nothing refreshes.
Reduce the number of calls on a page
A site page often holds many components. If five components each call their own Apex method, the page makes five requests. Several steps can reduce that:
- Combine related reads into one Apex method that returns a wrapper class, when the components always appear together.
- Fetch once in a parent component and pass the data to children through
@apiproperties. - Prefer
getRecordorgetRecordswhen components share the same record. - Render optional regions only when needed. A component inside a
lwc:ifblock that is false does not exist, so it does not fetch. Put a tab panel's content behind the condition that shows it.
Do not combine unrelated reads only for the sake of fewer calls. A slow query then delays everything that shares the response.
Keep each call cheap
The server side of a call is worth reviewing in the same way:
- Bound the result. Always use
LIMIT. For lists that can grow, add pagination with a "Load more" button.OFFSEThas a limit of 2,000 rows, so use a keyset filter onCreatedDateandIdfor deep paging. - Filter on indexed fields. Standard indexes cover Id, Name, CreatedDate, and lookup fields. A
LIKE '%text%'filter, as in the example, cannot use an index well. On a large object, prefer a prefix match ('text%') or a SOSL search. - Avoid queries in loops. One query for a set of Ids beats one query per Id. Governor limits make this a correctness issue as well as a speed issue.
- Return only what the page uses. Extra fields cost serialization time, bandwidth, and field-level security checks.
Static assets and the first load
Static resources are served with browser caching, so a large image or library you load once costs less on later pages. Still, the first load pays the full price. Keep these habits:
- Compress images and size them to the space they fill.
- Load a third-party library with
loadScriptonly in the component that needs it, and only when it is needed, not inconnectedCallbackof every component. - Keep custom CSS small. A short stylesheet that uses the site's styling hooks is cheaper than one that re-declares typography and colors.
Published sites can also be served through Salesforce's content delivery network, which caches public content closer to visitors. The details differ between Aura sites and LWR sites, so check the caching options for your site type in Experience Builder settings and in Salesforce documentation before relying on them. Cached public pages must not contain per-user data, so keep user-specific data in components that load after the page does.
Common mistakes
- Using
cacheable=trueon a method that depends on time or on data you expect to change immediately. - Passing
datainstead of the full wire result torefreshApex. - Letting
maxRowsbe unbounded in Apex because the page editor "only allows" small values. - Triggering a wire on every keystroke.
- Fetching data for a hidden tab, modal, or panel at page load.
- Measuring only as a logged-in admin. Test as a guest and as an external user, on a throttled connection and with an empty browser cache.
Exercise
A component wires a cacheable Apex method with { accountId: '$recordId' }. A user edits a field through a different component on the same page, and the list shows the old value. What do you change, and why does refreshApex(this.accounts.data) not fix it?
Show answer
Store the full object the wire delivers (for example in this.wiredAccounts) and call refreshApex(this.wiredAccounts) after the edit, or when the other component signals a change. refreshApex needs that wire result object, because it identifies which cache entry to invalidate and refetch. Passing only the data array gives it nothing to match, so the cached response stays in place.
Exercise
Why should a search box that drives a wired Apex method use a debounce timer, and what should the component do with that timer when it is removed from the page?
Show answer
Each change to a reactive wire parameter triggers a new request, so without a debounce a visitor typing a word causes one call per keystroke. A short timer (such as 300 ms) delays the update until typing pauses. In disconnectedCallback, clear the timer so it cannot run after the component is gone.