What is the difference between connectedcallback vs rendered callback?
I am currently developing a lightning web Component (LWC) for a particular real state company. How can I decide between using connected callback vs rendered callback for fetching the display property data effectively while ensuring a smooth experience for users?
In the context of Salesforce, here are the differences given between connectedcallback vs rendered callback:-
Connected
This is a type of lifecycle hook that is used in the scenario where when a component is inserted into the DOM. It is famous for tasks like initialization of component size or fetching data which usually doesn’t rely on the Components being rendered:-
connectedCallback() {
// Fetch property data when the component is inserted into the DOM
This.fetchPropertyData();
}
fetchPropertyData() {
// Code to fetch property data from server
}
Rendered callback
This is also a lifecycle hook which invoked after the component’s template has been rendered. It is very much suitable for tasks like manipulation of the DOM-based Components state:-
renderedCallback() {
// Manipulate DOM or perform actions after component rendering
This.highlightFeaturedProperty();
}
highlightFeaturedProperty() {
// Code to highlight featured property in the UI
}
For example consider a scenario where you need to display a loading indicator until the property data is fetched and then dynamically render the UI based on the fetched data, then you can use a combination of both lifecycle hooks:-
connectedCallback() {
this.isLoading = true;
this.fetchPropertyData();
}
renderedCallback() {
if (!this.isLoading) {
this.renderPropertyUI();
}
}
fetchPropertyData() {
// Code to fetch property data from server
// Once data is fetched, set isLoading to false
// and trigger rendering of UI
}
renderPropertyUI() {
// Code to dynamically render UI based on property data
}