Search code examples
polymerlit-element

LitElement lifecycle: before first render


Is there a way to execute a method exactly after the component has its properties available but before the first render? I mean something between the class contructor() and firstUpdated(). It sounds trivial, maybe in fact I'm missing something trivial..


Solution

  • The element's constructor is called when the element is created, either through the HTML parser, or for example through document.createElement

    The next callback is connectedCallback which is called when the DOM node is connected to the document. At this point, you have access to the element's light DOM. Make sure to call super.connectedCallback() before doing your own work, as the LitElement instance has some work to do here.

    The next callback is shouldUpdate, which is an optional predicate that informs whether or not LitElement should run its render cycle. Useful if for example, you have a single observed data property and destructure deep properties of it in render. I've found that it's best to treat this one as a predicate, and not to add all sorts of lifecycle logic inside.

    After that, update and render are called, then updated and firstUpdated. It's generally considered bad practice to perform side effects in render, and the occasions that you really need to override update are rare.

    In your case, it sounds very much like you should do your work in connectedCallback, unless you are relying on LitElement's rendered shadow DOM, in which case, you might consider running your code in firstUpdated, then calling this.requestUpdate() to force a second update (or changing some observed property in firstUpdated)

    More info: https://lit-element.polymer-project.org/guide/lifecycle