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 or hidden 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.

To check whether a component is connected to the DOM, you can use this.isConnected.

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.

connectedCallback() 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.

You can also use this hook to unsubscribe from a message channel.

See Also