Sub topic 12
When to Use Apex and When to Use Lightning Data Service
This chapter assumes you can write basic Apex and Lightning web components (LWC). It also assumes you have seen @wire and imperative Apex calls from earlier chapters. Here you will learn how to decide whether a component needs an @AuraEnabled method at all.
What Lightning Data Service gives you
Lightning Data Service (LDS) is the built-in layer that loads, caches and saves Salesforce records for components. You do not write server code to use it. You reach it through base components such as lightning-record-form, lightning-record-edit-form and lightning-record-view-form. You can also reach it through the lightning/uiRecordApi wire adapters and functions, such as getRecord, createRecord, updateRecord and deleteRecord.
LDS handles several things for you:
- It enforces sharing, object permissions and field-level security.
- It shares one client-side cache between components. When one component saves a record, other components showing that record update.
- It returns field values that respect the user's access, so you write no security code.
Apex gives you full control, but you own the security, the caching and the error handling.
Decision criteria
Start with LDS. Move to Apex only when LDS cannot do the job.
| Requirement | Better choice | Reason |
|---|---|---|
| Show or edit fields of one record | LDS | No code on the server, and the cache stays consistent |
| Create, update or delete one record | LDS | `createRecord` and `updateRecord` cover it |
| Query many records with filters or sorting | Apex | LDS reads one record at a time (or related lists) |
| Query across unrelated objects or use aggregates | Apex | SOQL features are not available in LDS |
| Change several records in one transaction | Apex | One DML call, one transaction |
| Run custom business logic or call a callout | Apex | Logic belongs on the server |
| Return a custom shape, such as totals plus records | Apex with a wrapper class | You define the response |
A worked comparison
Suppose a component must show the name and phone number of the current account. LDS needs only JavaScript:
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import ACCOUNT_NAME from '@salesforce/schema/Account.Name';
import ACCOUNT_PHONE from '@salesforce/schema/Account.Phone';
export default class AccountCard extends LightningElement {
@api recordId;
@wire(getRecord, { recordId: '$recordId', fields: [ACCOUNT_NAME, ACCOUNT_PHONE] })
account;
get name() {
return getFieldValue(this.account.data, ACCOUNT_NAME);
}
get phone() {
return getFieldValue(this.account.data, ACCOUNT_PHONE);
}
}Now suppose the component must list the account's 50 most recent contacts, sorted by name. That is a filtered query over many records, so it needs the getContacts method from earlier in this tutorial:
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
];
}
}The first case needs no Apex, and the second cannot be done well without it.
Mixing the two
You can use both in one component. A common pattern is to read with Apex and save with LDS, or the reverse. Be aware of one gotcha: LDS does not know about data that came from Apex. If a component saves a record through LDS, the LDS cache updates, but a cached Apex result does not. You must call refreshApex on the wired property, as shown earlier in this tutorial.
The reverse also applies. After an imperative Apex write, LDS may still hold older record values. Call notifyRecordUpdateAvailable from lightning/uiRecordApi with the changed record IDs to tell LDS to reload them.
Common mistakes
- Writing an Apex method that only queries one record by ID. LDS already does this with better caching.
- Skipping security in Apex because "LDS does it". Apex does not inherit LDS checks. Use
with sharingandWITH USER_MODEyourself. - Forgetting that Apex results and LDS records are cached separately.
Exercise
A component must let a user edit the Phone field of one Account and show the saved value in a second component on the same page. A teammate proposes an @AuraEnabled method for the update. What do you recommend, and why?
Show answer
Use LDS, for example lightning-record-edit-form or updateRecord. It enforces sharing and field-level security without extra code, and its shared cache updates the second component automatically. An Apex method would require you to write security checks and to refresh the second component yourself.
Exercise
A component saves several Contact records in one transaction through an imperative Apex call, while another component shows one of those Contacts with getRecord. What must you do so the second component shows the new values?
Show answer
Call notifyRecordUpdateAvailable with the IDs of the changed records. LDS does not know that Apex changed them, so its cached values are stale until you do.