What is the difference between calling Apex with @wire and calling it imperatively in LWC?
Answer
@wire
- Declarative and reactive: re-runs automatically when
$parameters change. - Requires the Apex method to be
@AuraEnabled(cacheable=true). - Results are cached client-side; refresh with
refreshApex. - Can't be triggered manually; ideal for read-only data on load.
Imperative
- You call the method like a promise on an event (button click, etc.).
- Works with non-cacheable methods, so it can perform DML.
- You control timing and handle
.then/.catchorasync/await.
javascript
async handleSave() {
try { await saveRecord({ rec: this.rec }); }
catch (e) { this.error = e.body.message; }
}
Use wire for reading data, imperative for DML or user-triggered calls.
lwcapexwire