What are the primary LWC lifecycle hooks, and in what order do they execute?
Answer
Basics: Lifecycle hooks are methods the platform calls at defined moments so you can initialize, touch the DOM, or clean up. They are standard methods on a class extending LightningElement.
How it works:
constructor(): instance created. Must callsuper()first. The component is not yet attached, so you cannot read attributes, children or public properties passed from the parent.connectedCallback(): inserted into the DOM. Public properties are set; do initialization here, subscribe to messages, add listeners, kick off imperative Apex. The template does not exist yet, sothis.template.querySelectorreturns null.render()(optional): returns which template to use; template is evaluated.- Children of the template are created and go through their own constructor, connected and render steps.
renderedCallback(): runs after render, child first, then parent. Use for DOM-dependent work, with a guard.disconnectedCallback(): removed from DOM; unsubscribe and clear timers.errorCallback(error, stack): on an ancestor, catches errors from descendants.
Advanced / deep dive: Order for nested components: parent constructor, parent connected, parent render, child constructor, child connected, child render, child rendered, parent rendered. Reconnection: if a component is removed and reinserted (for example by lwc:if toggling), connectedCallback and disconnectedCallback fire again, but class fields initialized earlier are retained only if the same instance is reused; with conditional removal a fresh instance is built. renderedCallback fires after every re-render, not just the first. Wire adapters provision after connection and may emit before or after first render, so never assume data is present in . Avoid heavy synchronous work in the constructor and connected phases, since it delays first paint.