Lifecycle
The framework calls constructor, connectedCallback, renderedCallback, disconnectedCallback, and errorCallback. render() chooses the template.
The hooks, in order
constructor runs first. Do not touch the DOM there, and do not read child elements. connectedCallback runs when the element is inserted. Children may still be unrendered.
renderedCallback runs after every render, including the first. disconnectedCallback runs when the element leaves the DOM. Clear timers and message subscriptions there. errorCallback(error, stack) runs when a descendant throws while rendering, in a lifecycle hook, or in a callback.
render()
Override render() to return a different imported HTML template. The return value is that template, from an import of the HTML file.
Prefer lwc:if when both layouts can live in one file. Salesforce recommends the conditional directives for that case. An extra template can only see the CSS file that shares its name.
renderedCallback can loop
If renderedCallback assigns a field that the template reads, the component renders again and the hook runs again. this.count = this.count + 1 on every pass never stops.
Load a script once by setting a guard that the template does not read, and return immediately when the guard is set. Do not assign template state from this hook unless a second render is what you want.
Example
javascript
import { LightningElement } from 'lwc';
export default class LoadOnce extends LightningElement {
loaded = false;
renderedCallback() {
if (this.loaded) {
return;
}
this.loaded = true;
}
}