• When it is called: It’s the very first hook that gets called when a component instance is created.
• Purpose:
• Initialize the component’s state or properties.
• Assign default values to variables.
• Do not perform DOM manipulations or use properties marked as reactive.
constructor() {
super(); // Always call `super()` first in the constructor
console.log('Constructor called');
}
connectedCallback(){
console.log('Component inserted into DOM');
// Example: Fetch data
fetchData();
}
connectedCallback() {
console.log('Component inserted into DOM');
// Example: Fetch data
fetchData();
}
console.log('Component rendered in DOM');
// Example: Manipulate DOM
const element = this.template.querySelector('.my-class');
element.classList.add('highlight');
}
• When it is called: Called when the component is removed from the DOM.
• Purpose:
• Clean up tasks like removing event listeners or cancelling subscriptions.
• Avoid memory leaks by cleaning up resources.
• Usage:
disconnectedCallback() {
console.log('Component removed from DOM');
// Example: Remove event listeners
this.removeEventListener('click', this.handleClick);
}
disconnectedCallback() {
console.log('Component removed from DOM');
// Example: Remove event listeners
this.removeEventListener('click', this.handleClick);
}
console.error('Error in component:', error);
console.error('Stack trace:', stack);
}