Custom Elements And The Light Dom

26 Jan 2025 - Ben

Custom Elements have their own lifecycle. This makes it orders of magnitude easier to render partial page updates. No matter how the html is added to the page, adding a custom element will kick in it’s own lifecycle. You’ll never get these bits of html that should do something, but the JavaScript hasn’t run on them because they were added after page load.

The Custom Element lifecycle gives us some of the reactive benefits of something like Alpine or React, but built directly into the browser. You’ll probably hit the limit of this reactivity very quickly, but both the lifecycle and reactivity are compelling reasons to use Custom Elements. And they integrate very well with something like React, for more complicated components.

Custom Elements also give you the ability to use the ShadowDOM. A form of encapsulation that ensures you’re interior elements are in their own little realm. But if I want a Custom Element to add behavior to the DOM, I still want to style it with CSS. So I rarely use the ShadowDOM. Instead, I use the “normal” DOM, or LightDOM, to make them easily accessible through CSS.

I haven’t done much more than think about this next part, but I think the ShadowDOM would be the right decision if I were creating a new input or similar control. Something that is complicated enough where I want to also give some styling control over using parts and slots. Since my day to day work is still mostly in React, I don’t do a lot of this. With React 19 and it’s full support for Custom Elements, many complex React controls could be rewritten as Custom Elements. They might even still have React in them, but they could be templated and share the web page much more easily.


Note: I prefer the name “Custom Element” because it reminds me more of html elements. Conversely, “Web Components” reminds me more of React components. Whatever you call them, they feel decidedly more like html elements than React components, so I prefer calling them Custom Elements. I know Custom Elements are really just one part of the Web Component suite of technologies, but I often hear them used interchangably.