The `@track` decorator in Lightning Web Components (LWC) is used to make a property reactive, meaning that changes to the property will cause the component to re-render. However, `@track` is used for internal state management within the component itself and is not intended for exposing properties to parent or other components.
Here’s a comparison:
- `@api`: Used to expose properties and methods to parent components. It makes the property or method public.
- `@track`: Used to make properties reactive within the component. It is used for internal state management.
Example using `@track`:
```javascript
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track internalState = {}; // This property is reactive within the component
handleChange(event) {
this.internalState.value = event.target.value;
}
}
```
In this example, `internalState` is a reactive property that will cause the component to re-render when its value changes, but it is not exposed to parent components.
Use `@api` when you need to expose properties or methods to parent components, and use `@track` for managing internal state that should trigger re-renders when changed.
import { LightningElement, track } from 'lwc';
export default class MyComponent extends LightningElement {
@track internalState = {}; // This property is reactive within the component
handleChange(event) {
this.internalState.value = event.target.value;
}
}
Preview:
downloadDownload PNG
downloadDownload JPEG
downloadDownload SVG
Tip: You can change the style, width & colours of the snippet with the inspect tool before clicking Download!
Click to optimize width for Twitter