DEV Community

Discussion on: Web Component developers do not connect with the connectedCallback (yet)

Collapse
 
alaindet profile image
Alain D'Ettorre • Edited

So, the best thing to do is just putting all the JavaScript code on the bottom of the body tag, as always, let the browser create a myriad of UnknownHTMLElement instances, the let it upgrade all instances when customElement.define() triggers. That opens the door to inability to interact and FOUC (en.wikipedia.org/wiki/Flash_of_uns...) for me, and yet it seems to be the best approach.

When I first started to learn about web components, I already knew Angular so I thought "ok connectedCallback() is like ngOnInit()" and actually it is, because if you need to read the parsed children you need to call ngAfterViewInit() and ngAfterContentInit() which are Angular-specific methods to interact with inner HTML, not ngOnInit(). Still, connectedCallback() seemed to be used by other developers more like "run this when the DOM is ready to be queried" more than "run this when the component is attached to the DOM, but maybe it's not ready yet". I guess it's just a little confusing all around and frameworks do a much better job than "standards" in giving simple flows and guarantees for me.

React is different, because a useEffect() without dependencies actually triggers after any first render (I'd say almost like a setTimeout()) and it actually works as intended.