Run Code When a Component Is Inserted or Removed from the DOM

The 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. To access the host element, use this. To access elements in a component’s template, use this.template.

connectedCallback() and disconnectedCallback() are standard lifecycle callbacks that follow web components standards.

Use connectedCallback() to interact with a component's environment. For example, use it to:

The 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.

The 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.

You can’t access child elements from the callbacks because they don’t exist yet.

Use 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 this.isConnected.

See Also