Sub topic 8
How client-side caching affects wired methods
This chapter explains what the Lightning Data Service client cache does with @AuraEnabled(cacheable=true) Apex methods. It covers why a wired component can show data that is out of date, and how to work with that behavior. It assumes you have read the earlier chapters on exposing an Apex method, importing it, and wiring it to a property or function.
What "cacheable=true" really promises
Marking an Apex method cacheable=true does two things:
- It tells the platform the method only reads data. The method must not perform DML, so it has no side effects.
- It allows the platform to store the method's return value in a client-side cache, keyed by the method and its parameters.
Because the method is read-only, the platform can safely reuse a stored result instead of calling the server again. This saves a network round trip and makes components render faster.
@wire requires this setting. An Apex method that is not cacheable cannot be wired. You can call it only imperatively.
public with sharing class ContactController {
@AuraEnabled(cacheable=true)
public static List<Contact> getContacts(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}How the cache behaves
The cache stores one entry for each unique combination of method and parameter values. Calling getContacts with account A and then with account B creates two entries.
When a component wires the method, the wire service follows this order:
- It builds the cache key from the method and the current parameter values.
- It looks for a stored result under that key.
- If a result exists, it provisions that data to the component immediately.
- It may also request fresh data from the server and, if the result differs, provision the new value.
Which of these steps happen depends on the platform. The exact lifetime and revalidation rules of the cache are not something you configure. Write components so they work whether the data came from the cache or from the server.
Consequences for your component
- Your wire handler can run more than once. A wired function may receive cached data first and newer data later. Do not assume it runs once per parameter change.
- The first render may show data quickly. Cached results make a component feel instant when a user returns to a page.
- Data can be stale. If another user, another component, or a trigger changes the records, your component may keep showing the older result until the cache is refreshed.
Why a save does not update your wired list
Suppose a component has a form that creates a Contact, and another component wires getContacts to show the list. After the save, the list still shows the old contacts.
This happens because Lightning Data Service tracks records that it loaded through its own adapters, such as getRecord. When you use lightning-record-form or createRecord, it can update those tracked records. A result that came from your custom Apex query is just a cached value under a key. The platform does not know which records your SOQL touched, so it cannot decide which cached Apex results to invalidate.
You must ask for fresh data yourself. There are two main ways:
- Call
refreshApexwith the value the wire provisioned. The next chapter covers it in detail. - Call the Apex method imperatively, which bypasses automatic provisioning (shown later in this chapter).
Mutating cached data
Wired data is read-only. The object that a wire provisions is frozen, so you cannot add to it or change its fields.
import { LightningElement, api, wire } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactCacheDemo extends LightningElement {
@api recordId;
rows;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts({ data }) {
if (data) {
// Wrong: data is read-only, so this throws in strict mode
// data.push({ Id: 'x', Name: 'New' });
// Right: copy first, then change the copy
this.rows = [...data];
}
}
}Copy the data before you sort, filter in place, or edit it. A shallow copy such as [...data] protects the array. If you plan to edit the objects inside, copy each object too:
this.rows = data.map((contact) => ({ ...contact }));This protection exists on purpose. The same cached object may be shared with other components that wire the same method with the same parameters. If one component could change it, the others would see the change.
Same parameters, shared result
Two components on a page that wire getContacts with the same accountId use the same cache entry. This has two effects.
- The second component can render from the stored result without waiting for the server.
- When one component refreshes the data, the other components that wire the same call receive the new value as well.
This sharing is useful, but it means you should not treat a wired result as private to your component.
Parameters and cache keys
The cache key includes the parameter values, so small differences matter.
| Call | Cache entry |
|---|---|
| `getContacts({ accountId: 'A' })` | Entry 1 |
| `getContacts({ accountId: 'A' })` from another component | Entry 1 (shared) |
| `getContacts({ accountId: 'B' })` | Entry 2 |
| `getContacts({ accountId: undefined })` | The wire does not provision data until the value is defined |
When a reactive parameter such as '$recordId' is undefined, the wire does not call the method. This avoids a useless request and a cache entry for an invalid call. If a parameter can legitimately change often, such as a search term typed by the user, each distinct value creates a new entry. For search boxes, consider debouncing input so you do not fire a call on every keystroke.
Avoiding the cache on purpose
Sometimes you need the latest data and do not want a stored value. You have several options.
Call the method imperatively
An imperative call to a cacheable method may still use the client cache, but you control when the call happens. It runs only when your code runs it:
import { LightningElement, api } from 'lwc';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactImperative extends LightningElement {
@api recordId;
rows;
errorMessage;
async handleLoad() {
try {
this.rows = await getContacts({ accountId: this.recordId });
this.errorMessage = undefined;
} catch (error) {
this.rows = undefined;
this.errorMessage = error.body ? error.body.message : error.message;
}
}
}Use a method that is not cacheable
If the data must always come from the server, leave off cacheable=true. You then call it imperatively, and each call goes to Apex. Do this only when freshness matters more than speed. It also lets the method perform DML, which a cacheable method cannot do.
Refresh after a known change
When you know your own code changed the data, refresh the wire. This keeps the benefit of caching for ordinary reads and replaces the stored value only when needed.
import { LightningElement, api, wire } from 'lwc';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactRefresh extends LightningElement {
@api recordId;
wiredResult;
rows;
@wire(getContacts, { accountId: '$recordId' })
wiredContacts(result) {
this.wiredResult = result;
if (result.data) {
this.rows = result.data;
}
}
handleRefresh() {
return refreshApex(this.wiredResult);
}
}Choosing an approach
| Situation | Suggested approach |
|---|---|
| Read-only data that rarely changes | Wire a cacheable method and accept cached results |
| Data changes after your own save | Wire the method and call `refreshApex` after the save |
| Data changes from outside your component | Refresh on a user action or on a timer, or call imperatively |
| Data must never be stale, or the method writes data | Non-cacheable method, called imperatively |
Common mistakes
- Expecting a wire to refetch after DML. The cache has no link between your DML and the cached SOQL result. Refresh explicitly.
- Changing wired data in place. The data is read-only. Copy it first.
- Assuming the handler runs once. A wired function can run again with the same or updated data.
- Putting side effects in a cacheable method. The method must be read-only. Platform behavior is undefined for writes, and DML in a cacheable method raises an error.
- Treating the cache as a security boundary. Sharing and field-level security are enforced when Apex runs. Another user's data is not served to you from your own cache, but you should still enforce access in Apex, as shown with
WITH USER_MODEabove.
Exercise
A component wires getContacts to a property and shows a list. A second component on the same page creates a new Contact for the same account. After the save, the list does not show the new Contact. Why does this happen, and what is one way to fix it?
Show answer
The wired result is a cached value for the method and the accountId parameter. Lightning Data Service does not know that the new Contact affects that custom SOQL result, so it does not invalidate the entry. To fix it, keep the value the wire provisioned and call refreshApex with it after the save, or load the data with an imperative call after the save.
Exercise
Your wired function runs data.sort((a, b) => a.Name.localeCompare(b.Name)) and throws an error. What is the cause, and how do you correct it?
Show answer
Wired data is read-only because it may be shared through the cache with other components. Sorting in place changes the array, which is not allowed. Copy the array first, for example this.rows = [...data].sort((a, b) => a.Name.localeCompare(b.Name));.
Exercise
Why does a wire with the parameter '$recordId' not call Apex while recordId is undefined, and why is that helpful for caching?
Show answer
A wire waits until all reactive parameters have defined values. Skipping the call avoids an invalid request and avoids storing a cache entry for parameters that have no meaning.