Introduction
In Lightning Web Components (LWC), variables can be either reactive or non-reactive, and this distinction is crucial for understanding how your component updates and re-renders.
Reactive Variables:
Reactive variables are special because when their values change, the component automatically re-renders to reflect those changes in the UI.
Characteristics:
Trigger a re-render when their value changes
Must be decorated with
@track
(for object properties) or@api
(for public properties)Primitive properties of a class are reactive by default (no decorator needed)
Example:
import { LightningElement, track } from 'lwc';
export default class ReactiveExample extends LightningElement {
// Primitive - reactive by default
count = 0;
// Object property - needs @track to be reactive
@track user = {
name: 'John',
age: 30
};
handleIncrement() {
this.count++; // Will trigger re-render
this.user.age++; // Will trigger re-render because of @track
}
}
Count: {count}
User Age: {user.age}
Non - Reactive Variables:
Non-reactive variables don’t trigger a re-render when their values change. They’re useful for storing data that doesn’t need to be reflected in the UI.
Characteristics:
Don’t trigger re-renders when changed
Can be private variables or object properties without
@track
More performant for data that doesn’t affect the UI
Example:
import { LightningElement } from 'lwc';
export default class NonReactiveExample extends LightningElement {
// Non-reactive object (no @track)
internalState = {
lastUpdated: null
};
// Non-reactive primitive (if not used in template)
privateCounter = 0;
handleClick() {
this.internalState.lastUpdated = new Date(); // Won't trigger re-render
this.privateCounter++; // Won't trigger re-render
// You'd need to manually query and update DOM elements if needed
const element = this.template.querySelector('.status');
if (element) {
element.textContent = `Updated at ${this.internalState.lastUpdated}`;
}
}
}
Key Differences:
Feature | Reactive Variables | Non-Reactive Variables |
---|---|---|
Triggers re-render | Yes | No |
Decorator needed | @track for objects, none for primitives | No decorator |
Performance impact | Higher (triggers render cycle) | Lower |
Use case | Data displayed in UI | Internal component state, calculations |
Template binding | Automatically updates | Requires manual DOM updates |
Conclusion
When to use each ?
-
-
Use reactive variables when the data needs to be reflected in the UI and should update automatically when changed.
-
Use non-reactive variables for internal calculations, temporary storage, or when you need to manually control when updates occur.
-
Remember that since Spring ’20, primitive properties are reactive by default, and object properties need @track
to be reactive for nested changes.