Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

LitElement connectedCallback() vs firstUpdate()

As documentation says:

connectedCallback fires each time a custom element is appended into a document-connected element

also:

firstUpdated fires after the first time your component has been updated and rendered

The problem is I can't figure out the difference between them. So what is the difference? when should I use connectedCallback and when firstUpdated lifecycle hooks?

like image 922
O. Shekriladze Avatar asked Aug 29 '26 21:08

O. Shekriladze


1 Answers

"Updating" is a LitElement lifecycle phase that happens batched and asynchronously, after properties are changed, the element is created, or requestUpdate() is called. LitElement performs rendering during an update. updated() and firstUpdated() are lifecycle callbacks that are called after updates. firstUpdated() is only called once, and it's intended to be used to do one time setup that depends on an update/render - like querying the shadow root for important elements.

connectedCallback() is called every time an element is connected to the document, and it's called synchronously by the browser. An element may be connected more than once if it has been disconnected and reconnected. Because connectedCallback() is called synchronously, it may be called before the first update/render, and the element might not have the state needed for some tasks that depend on rendering.

I would use the constructor and firstUpdated() for most one-time setup work, and connectedCallback() for work that depends on the tree structure the element's in - like firing events to connects to parents and ancestors.

like image 185
Justin Fagnani Avatar answered Sep 02 '26 04:09

Justin Fagnani



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!