Understanding the lifecycle of a custom element helps to better manage its behavior and performance. The primary lifecycle events that can be hooked into are:
constructor
- Called when the element is created.
connectedCallback
- Called when the element is added to the document.
disconnectedCallback
- Called when the element is removed from the document.
adoptedCallback
- Called when the element is moved to a new document.
These special methods are optionally defined directly on your custom element class.
Not defining them is perfectly fine, but if you do, they will be automagically called at the appropriate times.
The constructor
is where you can initialize your component's state.
It is called when the element is created, but it is important to note that the DOM is not yet ready at this point.
Therefore, you should avoid any DOM manipulation in the constructor.
What that means is it will not yet be a part of the DOM and any content to be contained within the element
will not yet be available.
You can, however, set up event listeners and initialize properties on the element itself.
The connectedCallback
is called when the element is added to the document.
This is where you can perform any setup that requires the element to be in the DOM, such as adding event listeners to, or manipulating content in the DOM.
It is also a good place to start any asynchronous operations that depend on the element being in the document.
The disconnectedCallback
is called when the element is removed from the document.
This is where you should clean up any resources that are no longer needed, such as removing event listeners or stopping timers.
Failing to do this can lead to memory leaks and other performance issues.
The adoptedCallback
is called when the element is moved to a new document.
This can happen when the element is moved between different browsing contexts, such as iframes or shadow DOMs.
This is best used when there is one-time setup that needs to happen per document.