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.

Tip

connectedCallback() 

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.

1<template>
2  <div>Some content</div>
3</template>
1import { LightningElement } from "lwc";
2
3export default class ConnectedCallbackExample extends LightningElement {
4  connectedCallback() {
5    // This doesn't work
6    const div = this.template.querySelector("div");
7  }
8}

disconnectedCallback() 

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.

Don't mark lifecycle hooks as async 

connectedCallback() and disconnectedCallback() are synchronous. The framework doesn’t await a promise that’s returned from a lifecycle hook. If you mark a hook as async, code after an await runs after the framework moves on, which causes unpredictable order of execution relative to rendering, parent and child callbacks, and event handlers.

To run async work from a lifecycle hook, call a separate async method from the synchronous hook.

1import { LightningElement } from "lwc";
2
3export default class extends LightningElement {
4  connectedCallback() {
5    this.loadData();
6  }
7
8  async loadData() {
9    const result = await fetchSomething();
10    // Update reactive properties here.
11  }
12}

See Also