5

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?

O. Shekriladze
  • 1,346
  • 1
  • 19
  • 36

1 Answers1

14

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

Justin Fagnani
  • 10,483
  • 2
  • 27
  • 37
  • what do you mean exactly with "connected to the document"? Simple created or something specific? – alfredopacino Oct 18 '19 at 09:39
  • Connected to the document means connected to a parent node that is also connected to the document, ie the node has a parent, which has a parent, etc., until the parent is the window's document. – Justin Fagnani Jan 05 '20 at 04:52