What is Lightning Data Service (LDS) in LWC, and what are the benefits of using lightning/uiRecordApi?
Answer
Basics: Instead of writing an Apex controller for every read or save, you ask LDS for a record by Id and fields. It handles caching, so two components showing the same record make one request, and an edit in one updates the other automatically.
How it works:
- Import adapters and functions from
lightning/uiRecordApi:getRecord(wire),getFieldValue,getFieldDisplayValue,createRecord,updateRecord,deleteRecord,getRecordNotifyChange/notifyRecordUpdateAvailable, and helpers likegenerateRecordInputForUpdate. - Import field references from schema:
import NAME from '@salesforce/schema/Account.Name';which gives compile-time checking and dependency tracking. - Wire:
@wire(getRecord, { recordId: '$recordId', fields: [NAME] }). - Write:
updateRecord({ fields: { Id, [NAME.fieldApiName]: value } }). - LDS invalidates and refreshes affected wires after writes.
Advanced / deep dive: Benefits: less code, no Apex test coverage burden, consistent security (CRUD, FLS and sharing enforced), cache shared across components, and performance. Limits: it works one record at a time, no aggregate queries, no complex joins or multi-object transactions, limited to what the UI API supports, and every field must be listed (use optionalFields when a user may lack access, to avoid failing the whole request). getRecordUi is a legacy approach that returns layout metadata; prefer getRecord and getObjectInfo (verify current guidance in release notes). Reach for Apex for bulk operations, business logic across objects, or SOQL beyond UI API capability. LDS also underpins base components such as and works in Salesforce mobile with offline support for supported scenarios. Components with on record pages get the Id automatically.