Sub topic 5
Making the wire reactive with $recordId
This chapter explains how a wire re-runs when a component property changes. It assumes you know JavaScript modules, promises, and async/await. It also assumes you know the structure of a Lightning web component (template, class, metadata file), the @api decorator, and the recordId property on record pages. The earlier chapters in this tutorial covered @wire, schema imports, and basic getRecord use. This chapter builds on them.
What "reactive" means for a wire
A wire adapter receives a configuration object. Each value in that object is either fixed or reactive. A fixed value is read once. A reactive value is tied to a property of your component. When that property changes, the wire service calls the adapter again with the new configuration and provisions a new result.
You mark a value as reactive by writing a string that starts with $ and names a property on the component:
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
account;Here '$recordId' is not a literal ID. It is an instruction: "read this.recordId and use its current value." The $ prefix only works inside the configuration object of @wire, and only as the first character of a string value.
Why the wire needs this
A component rarely knows its record ID when it is constructed. On a record page, the platform sets recordId after the component is created. In a parent-child layout, a parent may change the ID later, for example when a user picks a different row in a list.
Without a reactive parameter you would have to call the data layer yourself each time the ID changes. With $recordId, the wire service watches the property and handles that for you.
The lifecycle of a reactive wire
The wire service does not call the adapter with an undefined reactive value. It waits until every reactive parameter has a defined value. Then it provisions data. After that, each change to a reactive property triggers a new call.
The results arrive asynchronously. For a short time after the ID changes, your property may still hold the previous result or be empty. Do not assume the data matches the new ID until the next result arrives.
Which values can be reactive
Any value in the configuration object can be reactive, not only recordId. The following example makes both the ID and the list of fields depend on component state. The class exposes a plain fieldsToLoad property that the template or a parent can change:
import { LightningElement, api, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
import INDUSTRY_FIELD from '@salesforce/schema/Account.Industry';
import PHONE_FIELD from '@salesforce/schema/Account.Phone';
export default class AccountViewer extends LightningElement {
@api recordId;
showContactInfo = false;
get fieldsToLoad() {
return this.showContactInfo
? [NAME_FIELD, INDUSTRY_FIELD, PHONE_FIELD]
: [NAME_FIELD, INDUSTRY_FIELD];
}
@wire(getRecord, { recordId: '$recordId', fields: '$fieldsToLoad' })
account;
toggleContactInfo() {
this.showContactInfo = !this.showContactInfo;
}
}Two points matter here:
- The value
'$fieldsToLoad'refers to a getter. Reactive parameters can name getters as well as fields. - When
showContactInfochanges, the getter returns a new array. The wire service sees a new value forfieldsToLoadand calls the adapter again.
What counts as a change
The wire service compares the new value of a reactive property with the previous one. It does not detect changes made inside an object or array that keeps the same identity. This is the most common source of "my wire does not refresh" bugs.
Consider this code:
// Does not trigger the wire again: same array, mutated in place
this.fieldList.push(PHONE_FIELD);
// Triggers the wire again: a new array
this.fieldList = [...this.fieldList, PHONE_FIELD];Always replace the value rather than mutating it. A getter that builds a new array on every access, as in the previous example, also works, because the result is a new object each time the dependency changes.
Reactive parameters and `undefined`
Because the wire waits for defined values, you can control when it runs by controlling the property. Setting a reactive property to undefined pauses the wire. No request is made until the property has a value again.
The behavior is useful for conditional loading:
import { LightningElement, wire } from 'lwc';
import { getRecord } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Contact.Name';
export default class ContactPicker extends LightningElement {
selectedContactId;
@wire(getRecord, { recordId: '$selectedContactId', fields: [NAME_FIELD] })
contact;
handleSelect(event) {
this.selectedContactId = event.detail.recordId;
}
handleClear() {
this.selectedContactId = undefined;
}
}Until the user selects a contact, selectedContactId is undefined and the wire does not fire. After handleClear, the wire stops requesting data again. Check your template for the result of the last request, since contact.data may still hold the old value. If the UI must go blank, track the selection in your own state and render based on that.
Reactive wires on a function
The same $ syntax works when you wire to a function instead of a property. The function runs each time the wire provisions a new result:
import { LightningElement, api, wire } from 'lwc';
import { getRecord, getFieldValue } from 'lightning/uiRecordApi';
import NAME_FIELD from '@salesforce/schema/Account.Name';
export default class AccountNameTracker extends LightningElement {
@api recordId;
currentName;
@wire(getRecord, { recordId: '$recordId', fields: [NAME_FIELD] })
handleAccount({ data, error }) {
if (data) {
this.currentName = getFieldValue(data, NAME_FIELD);
} else if (error) {
this.currentName = undefined;
}
}
}When recordId changes, the wire service calls handleAccount again with the result for the new ID.
Rules and limits
- The reactive string must start with
$and name a property of the component, such as'$recordId'. A path such as'$record.id'is allowed in some adapters for nested values, but a plain property is the form to rely on here. - The property can be a public
@apiproperty, a private field, or a getter. - The wire service reads the property from the component instance. It does not read local variables or values you compute inline in the decorator.
- Do not put
$inside a larger string.'prefix$recordId'is a literal string, not a reactive reference. - Never assign to the wired property from your own code. The wire service owns it.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| The wire never returns data | The reactive property stays `undefined`, for example `recordId` is not set outside a record page | Set the property, or check where the component is placed |
| The adapter receives the literal text `$recordId` | The string was written without quotes issues or with a template literal that evaluated early | Use the single-quoted string `'$recordId'` in the configuration object |
| The wire does not refresh after a field list change | The array was mutated in place | Assign a new array |
| Stale data shows after the ID changes | The previous result stays in place until the new one arrives | Render based on state you control, or check the record ID in the result |
| An error appears for a missing field or ID | The ID is valid but the user cannot access it, or the field is not accessible | Handle `error` in the wire result |
Putting it together
A typical pattern uses @api recordId for the page context and a private property for user selection. Both feed one wire. The template checks data and error as shown in earlier chapters. Because the wire handles each change, you do not write code to call the adapter, cancel old calls, or merge results.
Exercise
A component has @wire(getRecord, { recordId: '$selectedId', fields: '$fieldList' }) record;. The code calls this.fieldList.push(PHONE_FIELD) to add a field, but the wire does not run again. Why does this happen, and how do you fix it?
Show answer
push changes the array in place, so fieldList still refers to the same array object. The wire service sees no new value and does not call the adapter. Assign a new array instead, for example this.fieldList = [...this.fieldList, PHONE_FIELD];.
Exercise
A component sets selectedId to undefined when the user clicks "Clear". The wire is @wire(getRecord, { recordId: '$selectedId', fields: [NAME_FIELD] }) contact;. What happens to the wire request, and what should the template do if it must show an empty state?
Show answer
The wire service stops calling the adapter while selectedId is undefined, so no new request is made. The contact property may still hold the last result, so the template should depend on your own state, such as whether selectedId is set, to decide whether to show the data or the empty state.