Run Code When a Component Is Inserted or Removed from the DOM
connectedCallback() lifecycle hook fires when a component is inserted into the DOM. The
disconnectedCallback() lifecycle hook fires when a component is removed from the DOM.
Both hooks flow from parent to child. You can’t access child elements from the callbacks because they don’t exist yet. To access the host element, use
this. To access elements in a component’s template, use
connectedCallback() to interact with a component's environment. For example, use it to:
- Establish communication with the current document or container and coordinate behavior with the environment.
- Perform initialization tasks, such as fetch data, set up caches, or listen for events
- Subscribe and Unsubscribe from a Message Channel.
connectedCallback() hook is invoked with the initial properties passed to the component. If a component derives its internal state from the properties, it's better to write the logic in a setter than in
connectedCallback(). For sample code, see this StackExchange post by Salesforce engineer, Pierre-Marie Dartus.
connectedCallback() hook can fire more than one time. For example, if you remove an element and then insert it into another position, such as when you reorder a list, the hook fires several times. If you want code to run one time, write code to prevent it from running twice.
disconnectedCallback() to clean up work done in the
connectedCallback(), like purging caches or removing event listeners.
To check whether a component is connected to the DOM, you can use