Sub topic 12
When to use something other than refreshApex
This chapter assumes you have read the earlier chapters. You should know how a wire provisions a result object, how refreshApex takes that object, and why updates go through a non-cacheable Apex method. Here you will learn where refreshApex stops fitting and what to use instead.
What refreshApex is for
refreshApex does one job. You hand it the result of a wired Apex method, and it re-runs that method with the current parameters. It then provisions the new result to the same wire.
That fits when all of these are true:
- The data comes from a
@wireof a cacheable Apex method. - Your own component, or code you control, knows when the data may have changed.
- Re-running the whole Apex query is an acceptable cost.
When one of these is false, another tool is usually simpler or more correct. The sections below cover the common cases.
Decision overview
Use Lightning Data Service for record data
If the component only displays or edits single records and a few fields, you may not need Apex at all. Lightning Data Service (LDS) is the framework layer behind lightning/uiRecordApi. It has its own cache, shared across components on the page, and it keeps that cache consistent for you.
With LDS you get the following:
getRecordfor reading fields.updateRecord,createRecordanddeleteRecordfor writing. After a successfulupdateRecord, wires that read the same record update automatically. You call nothing else.- Automatic respect for field-level security and sharing.
If you wrote a cacheable Apex method only to read a record by Id, replacing it with getRecord removes the refresh problem completely.
When Apex changes a record behind LDS's back
Sometimes you must use Apex for the write, for example because the save touches several objects or runs custom logic. LDS does not know the record changed. Use notifyRecordUpdateAvailable from lightning/uiRecordApi. It tells LDS that the listed records changed on the server, so LDS re-fetches them for the wires that use them.
import { LightningElement, api, wire } from 'lwc';
import { getRecord, notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import updateEmail from '@salesforce/apex/ContactController.updateEmail';
const FIELDS = ['Contact.Name', 'Contact.Email'];
export default class ContactCard extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: FIELDS })
contact;
async handleSave(event) {
const { email } = event.detail;
await updateEmail({ contactId: this.recordId, email });
await notifyRecordUpdateAvailable([{ recordId: this.recordId }]);
}
}This is the LDS counterpart of the DML-then-refresh pattern from earlier chapters. The write goes through Apex, and then you signal the cache.
Call Apex imperatively when you want control
A wire is declarative. The framework decides when to call the method, and it may serve the result from the cache. That is the right default for read-heavy screens. It is a poor fit in these cases:
- The data is loaded only after a user action, such as a button click or a search.
- The result should reflect the server at the moment of the call, every time.
- You need to branch on the result, chain calls, or show a spinner around one specific request.
Then drop the wire and call the method imperatively. If the data must never come from the client cache, drop cacheable=true too. Apex methods without it are not cached by the framework. They are also allowed to perform DML.
public with sharing class ContactFreshController {
@AuraEnabled
public static List<Contact> getContactsFresh(Id accountId) {
return [
SELECT Id, Name, Email
FROM Contact
WHERE AccountId = :accountId
WITH USER_MODE
ORDER BY Name
LIMIT 50
];
}
}import { LightningElement, api } from 'lwc';
import getContactsFresh from '@salesforce/apex/ContactFreshController.getContactsFresh';
export default class ContactListFresh extends LightningElement {
@api recordId;
contacts = [];
error;
connectedCallback() {
this.loadContacts();
}
async loadContacts() {
try {
this.contacts = await getContactsFresh({ accountId: this.recordId });
this.error = undefined;
} catch (e) {
this.error = e;
this.contacts = [];
}
}
async handleSave(event) {
// Imagine another imperative call here that saves the change.
await this.loadContacts();
}
}The trade-off is that you give up three things the wire provides:
- Automatic re-run when a reactive parameter changes.
- Cache reuse across components that wire the same method with the same parameters.
- Automatic provisioning of
dataanderror.
You manage loading state and errors yourself. For a screen that loads once and refreshes on a button, that is a fair price.
Let the parameters do the refreshing
A wire re-runs when a reactive parameter changes. Sometimes you can use this on purpose instead of calling refreshApex. If the query depends on a value that you can change, such as a "version" counter, changing it triggers a new request.
This works, but it is a workaround. Cached results are keyed on the parameters, so a counter that you increment forces a new cache entry on each change. It also adds a parameter to the Apex method that has no business meaning. Prefer refreshApex when you have the wired result in hand. Use the counter only in the rare case where you cannot reach the result object, for example when the trigger comes from a sibling component.
Changes made by other users or processes
refreshApex runs when your code decides to run it. It cannot know that another user edited a contact, or that a scheduled job updated a field. If staleness comes from outside your component, you need a signal from the server.
| Situation | Approach | Notes |
|---|---|---|
| The user edits data in your component | `refreshApex` after the DML call | Covered in earlier chapters. |
| The user edits the record in another component on the page | `notifyRecordUpdateAvailable`, or a custom event up and down the component tree | LDS wires update on their own. Apex wires need your own signal. |
| Another user or a background job changes the data | Platform events or Change Data Capture through `lightning/empApi`, then `refreshApex` in the handler | Needs event setup on the org and a subscription in `connectedCallback`. |
| The page-level Refresh action must reload your component | The `lightning/refresh` module (`RefreshEvent`, `registerRefreshHandler`) | For Lightning Experience pages. Check the current docs for supported contexts. |
| You need updates every few seconds | Polling with `setInterval` and an imperative call | Simple, but costs API requests and battery. Use sparingly. |
For the event-based option, the pattern is to subscribe once and refresh inside the callback:
import { LightningElement, api, wire } from 'lwc';
import { subscribe, unsubscribe } from 'lightning/empApi';
import { refreshApex } from '@salesforce/apex';
import getContacts from '@salesforce/apex/ContactController.getContacts';
export default class ContactListLive extends LightningElement {
@api recordId;
subscription;
@wire(getContacts, { accountId: '$recordId' })
contacts;
async connectedCallback() {
this.subscription = await subscribe(
'/data/ContactChangeEvent',
-1,
() => refreshApex(this.contacts)
);
}
disconnectedCallback() {
if (this.subscription) {
unsubscribe(this.subscription, () => {});
}
}
}Two things to watch. Change Data Capture must be enabled for Contact in Setup, or no events arrive. A busy object also fires many events, so a handler that refreshes on each one can flood the server. Debounce the refresh if events arrive in bursts.
Comparing the options
| Option | Cache behavior | You manage | Best for |
|---|---|---|---|
| `refreshApex` on an Apex wire | Re-fetches, then updates the cache | Keeping the wired result | Lists and custom queries that your component changes |
| `getRecord` with `updateRecord` | LDS keeps it in sync | Nothing | Single records and standard fields |
| `notifyRecordUpdateAvailable` | Asks LDS to re-fetch | The list of changed record Ids | Apex writes that affect LDS-backed wires |
| Imperative non-cacheable call | No client cache | State, errors, timing | On-demand loads and always-fresh data |
| Event subscription plus refresh | Re-fetches on a server signal | Subscriptions and cleanup | Multi-user or background changes |
Common mistakes when switching approaches
- Keeping
cacheable=trueon a method and then calling it imperatively, expecting a fresh read every time. Cacheable results can be served from the client cache, so use a non-cacheable method when freshness is the point. - Using
notifyRecordUpdateAvailableto refresh a wired Apex list. It is for LDS wires. - Subscribing to events without unsubscribing in
disconnectedCallback. Subscriptions leak and handlers fire for components that no longer exist. - Adding polling when a single event subscription would do.
- Writing Apex to read one record by Id.
getRecordis shorter, and its cache is kept consistent by LDS.
Exercise
A component shows an Account's name and phone through a cacheable Apex wire. A "Save" button calls a non-cacheable Apex method that updates the Account and also writes a related audit record. After saving, the name still shows the old value. Name two different ways to fix this and say which one you would choose if the component could be rewritten.
Show answer
First, keep the Apex wire and call refreshApex on the wired result after the save call resolves. Second, replace the Apex read with @wire(getRecord, ...) for Account fields and call notifyRecordUpdateAvailable([{ recordId }]) after the Apex save, since Apex changed the record behind LDS. If the component can be rewritten, the second is the better choice. The data is a single record, getRecord respects field-level security and sharing, and LDS keeps its cache consistent across components. If the save could use updateRecord instead of Apex, you would not need the notify call, because LDS updates the cache itself. The audit record would then have to be written by a trigger or flow.
Exercise
Users report that a wired list of contacts is stale when a colleague edits a contact in another browser. The editing user's own component refreshes correctly. Why does refreshApex not help here, and what would you add?
Show answer
refreshApex only runs when your code calls it, and nothing in the first user's browser knows about the colleague's edit. You need a server-side signal. Enable Change Data Capture for Contact, subscribe to /data/ContactChangeEvent with lightning/empApi in connectedCallback, and call refreshApex on the wired result in the callback. Unsubscribe in disconnectedCallback, and consider debouncing the refresh if events arrive in bursts.