What is the purpose of the connectedCallback lifecycle hook, and when is it typically utilized?
Answer
Basics: Every LWC has a lifecycle: constructor -> connectedCallback -> render -> renderedCallback (after each render), and disconnectedCallback when removed. connectedCallback is the first hook where the component is attached to a document and public properties set by the parent are available. Use it for one-time setup such as calling imperative Apex, registering listeners on window/document, subscribing to Lightning Message Service or empApi, and reading URL state.
How it works: The parent is created and connected first, then its children (flow is parent to child). When the framework attaches the host element it calls connectedCallback(); afterwards the template renders and renderedCallback() fires. Because the component has not rendered yet, this.template.querySelector(...) returns null for your own template elements. If the component is removed and re-inserted (for example by lwc:if toggling, or being moved in the DOM) the hook runs again, so it can fire many times in one component instance's life.
Advanced / deep dive: Do not use constructor for work beyond calling super() and initializing fields: you cannot read @api values or set attributes on the host there. @wire provisioning also starts around connection, so you rarely need connectedCallback for data that a wire adapter can supply; prefer @wire for reads (cacheable, reactive) and imperative calls only for user-triggered or non-cacheable work. Do not make it async and forget error handling: an unhandled rejection will not break rendering but silently leaves the UI empty. Always pair registrations made here with removal in , otherwise re-insertion registers duplicates.