@TRACK(to make property reactive) AND @API(to expose property to different component or parent class )
Fri Dec 20 2024 10:46:54 GMT+0000 (Coordinated Universal Time)
Saved by
@mdfaizi
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;
}
}
content_copyCOPY
Comments