Sub topic 12
When to use Apex and when to use Lightning Data Service
This chapter assumes you have read the earlier chapters on @AuraEnabled methods, @wire calls, imperative calls, and security in controller code. You should also know the basics of Lightning web components (LWC) and SOQL.
Every call to Apex adds code to write, test, and secure. Lightning Data Service (LDS) can often do the same job with no Apex at all. This chapter gives you criteria for choosing between them.
What Lightning Data Service is
Lightning Data Service is the client-side layer that reads and writes Salesforce records on behalf of your component. You use it through base components such as lightning-record-form, lightning-record-edit-form, and lightning-record-view-form. You can also use it through JavaScript modules such as lightning/uiRecordApi.
LDS does these things for you:
- It enforces sharing, object permissions, and field-level security. You write no security code.
- It caches records on the client. Components on the same page share that cache, so a record is fetched once.
- It keeps components in sync. When one component saves a record, other components showing that record update.
- It needs no Apex class, no test class, and no code coverage.
LDS works with the Salesforce UI API. It can only do what that API supports, and that limit decides when you need Apex.
What LDS can and cannot do
LDS works on records by ID, on list views, and on related lists. It cannot run arbitrary queries or arbitrary server logic.
| Requirement | LDS | Apex |
|---|---|---|
| Show or edit fields of one record | Yes | Works, but unnecessary |
| Create, update, or delete one record | Yes | Works |
| Show a standard list view or a related list | Yes | Works |
| Filter with custom SOQL conditions across objects | No | Yes |
| Aggregate queries (`COUNT`, `SUM`, `GROUP BY`) | No | Yes |
| SOSL search | No | Yes |
| Change many records in one transaction | No | Yes |
| Callouts to external systems | No | Yes |
| Custom business logic or validation before saving | Limited | Yes |
| Objects the UI API does not support | No | Yes |
Start with LDS
Use LDS first. Move to Apex only when you hit a requirement from the table that LDS cannot meet. A component that reads one account needs no controller:
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
export default class AccountHeader extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD, PHONE_FIELD] })
account;
get name() {
return getFieldValue(this.account.data, NAME_FIELD);
}
get phone() {
return getFieldValue(this.account.data, PHONE_FIELD);
}
}The schema imports (@salesforce/schema/Account.Name) have two benefits. Salesforce checks that the fields exist, and it records the dependency, so a field cannot be deleted while the component uses it. A string such as 'Account.Name' also works, but it gives you neither benefit.
The getRecord adapter returns only the fields you request. If the user has no read access to a field, the request fails rather than silently returning a blank. That behavior is the same enforcement you would otherwise add with WITH USER_MODE.
Choose Apex when the requirement exceeds the UI API
Aggregates and custom queries
LDS has no way to ask "how many opportunities does this account have in each stage?" That needs a GROUP BY query, so it needs Apex. The wrapper class from the earlier chapter keeps the response clean:
public with sharing class OpportunityStatsController {
public class StageCount {
@AuraEnabled public String stage;
@AuraEnabled public Integer total;
}
@AuraEnabled(cacheable=true)
public static List<StageCount> getStageCounts(Id accountId) {
List<StageCount> results = new List<StageCount>();
for (AggregateResult ar : [
SELECT StageName, COUNT(Id) total
FROM Opportunity
WHERE AccountId = :accountId
WITH USER_MODE
GROUP BY StageName
]) {
StageCount sc = new StageCount();
sc.stage = (String) ar.get('StageName');
sc.total = (Integer) ar.get('total');
results.add(sc);
}
return results;
}
}This method is read-only, so cacheable=true is correct and the component can call it with @wire.
Multi-record transactions and custom logic
createRecord and updateRecord handle one record per call. If a business action must change many records, and must either all succeed or all fail, put it in one Apex method. The platform then runs it as a single transaction. Callouts, complex validation, and calls to other Apex services belong in Apex for the same reason.
Anything LDS does not cache correctly
Cacheable Apex results are cached per method and parameter set. They are not tied to record changes. If your component needs data that must always reflect the current record state, LDS is the better fit, because it updates automatically. If you must use Apex for a read, plan for refreshApex, as the previous chapter explains.
Combining the two
You can use both in one component, and often you should. LDS handles the record the user is looking at. Apex handles the extra work. There is one gotcha: LDS does not know that your Apex method changed records. Its cache goes stale, and the page shows old values.
notifyRecordUpdateAvailable from lightning/uiRecordApi fixes this. You pass it the IDs of the records your Apex code changed. LDS then refreshes any component that displays them.
public with sharing class OpportunityActionsController {
@AuraEnabled
public static List<Id> closeOpenOpportunities(Id accountId) {
List<Opportunity> open = [
SELECT Id, StageName
FROM Opportunity
WHERE AccountId = :accountId AND IsClosed = false
WITH USER_MODE
];
for (Opportunity o : open) {
o.StageName = 'Closed Lost';
}
update as user open;
return new List<Id>(new Map<Id, Opportunity>(open).keySet());
}
}import { LightningElement, api } from 'lwc';
import { notifyRecordUpdateAvailable } from 'lightning/uiRecordApi';
import closeOpenOpportunities from '@salesforce/apex/OpportunityActionsController.closeOpenOpportunities';
export default class CloseOpportunities extends LightningElement {
@api recordId;
error;
async handleClose() {
try {
const ids = await closeOpenOpportunities({ accountId: this.recordId });
await notifyRecordUpdateAvailable(ids.map((id) => ({ recordId: id })));
this.error = undefined;
} catch (error) {
this.error = error.body ? error.body.message : error.message;
}
}
}The method is not cacheable because it performs DML, so you call it imperatively. After the call succeeds, the component tells LDS which records changed.
Use notifyRecordUpdateAvailable for LDS data. Use refreshApex for results that came from a cacheable Apex method. They solve the same staleness problem for different caches.
A decision flow
Trade-offs to weigh
- Code to maintain. Each Apex method needs a test class, 75% organization-wide coverage, and security review. LDS has none of that cost.
- Security. LDS enforces sharing and field-level security by design. In Apex you must remember
with sharingandWITH USER_MODEoras userevery time. A missed check is a data exposure bug. - Performance. LDS shares a client cache across components. Two Apex wires with the same parameters share a cache entry as well, but two different Apex methods that read the same record each fetch it separately.
- Flexibility. Apex can do anything a server can do. LDS is limited to the UI API.
- Staleness. Cached Apex data can be out of date after changes. LDS handles this automatically for its own writes.
Common mistakes
- Using Apex for simple record reads. This adds code, tests, and security duties with no benefit.
- Forcing LDS to do aggregation. If you load hundreds of records with LDS and sum them in JavaScript, you move work to the client and risk governor-style limits on response size. A
GROUP BYquery in Apex is the right tool. - Forgetting to notify LDS after Apex DML. The page keeps showing old values until the user reloads.
- Mixing up the two refresh tools.
refreshApextakes a wired Apex result.notifyRecordUpdateAvailabletakes record IDs.
Exercise
A component on an Account page must show the account's Name and Phone, and also show total open opportunity amount grouped by stage. A button also closes all open opportunities in one transaction. Which parts use LDS and which use Apex? What must the component do after the button's Apex call succeeds?
Show answer
Use LDS (getRecord with schema-imported fields, or lightning-record-view-form) for Name and Phone, because that is a single record with no custom logic. Use a cacheable Apex method with a GROUP BY query for the grouped amounts, because LDS cannot aggregate; call it with @wire. Use a non-cacheable Apex method, called imperatively, for closing all open opportunities, because it changes many records in one transaction. After it succeeds, call notifyRecordUpdateAvailable with the changed record IDs so LDS refreshes any component showing them, and call refreshApex on the wired stage totals so the grouped amounts are fetched again.
Exercise
Why is refreshApex not the right way to refresh a component that uses getRecord?
Show answer
refreshApex refreshes the result of a wired Apex method. getRecord is an LDS adapter with its own cache. For LDS data, use notifyRecordUpdateAvailable after a change made outside LDS, such as an Apex update.