{
  "$type": "site.standard.document",
  "coverImage": {
    "$type": "blob",
    "ref": {
      "$link": "bafkreidfvvfzpvsbnhfxukperws7ja5vrd6om5ytzllk6jm7qjkwkjg32e"
    },
    "mimeType": "image/png",
    "size": 54794
  },
  "description": "Web components can dramatically loosen the coupling of JavaScript frameworks. To prove it, we're going to do something kinda crazy: build an app where every single component is written in a different JavaScript framework.",
  "path": "/words/web-components-eliminate-javascript-framework-lock-in/",
  "publishedAt": "2023-11-27T00:00:00Z",
  "site": "at://did:plc:vrrdgcidwpvn4omvn7uuufoo/site.standard.publication/3mmyfl3pxzi2a",
  "tags": [
    "javascript",
    "react",
    "solid",
    "svelte"
  ],
  "textContent": "We've seen a lot of great posts about web components lately.\nMany have focused on the burgeoning HTML web components pattern, which eschews shadow DOM in favor of progressively enhancing existing markup.\nThere's also been discussion — including this post by yours truly — about fully replacing JavaScript frameworks with web components.\n\nThose aren't the only options, though.\nYou can also use web components in tandem with JavaScript frameworks.\nTo that end, I want to talk about a key benefit that I haven't seen mentioned as much: web components can dramatically loosen the coupling of JavaScript frameworks.\n\nTo prove it, we're going to do something kinda crazy: build an app where every single component is written with a different framework.\n\nIt probably goes without saying that you should not build a real app like this!\nBut there are valid reasons for mixing frameworks.\nMaybe you're gradually migrating from React to Vue.\nMaybe your app is built with Solid, but you want to use a third-party library that only exists as an Angular component.\nMaybe you want to use Svelte for a few \"islands of interactivity\" in an otherwise static website.\n\nHere's what we're going to create: a simple little todo app based loosely on TodoMVC.\n\nAs we build it, we'll see how web components can encapsulate JavaScript frameworks, allowing us to use them without imposing broader constraints on the rest of the application.\n\nWhat's a Web Component?\n\nIn case you're not familiar with web components, here's a brief primer on how they work.\n\nFirst, we declare a subclass of HTMLElement in JavaScript. Let's call it MyComponent:\n\nThat call to attachShadow in the constructor makes our component use the shadow DOM, which encapsulates the markup and styles inside our component from the rest of the page.\nconnectedCallback is called when the web component is actually connected to the DOM tree, rendering the HTML contents into the component's \"shadow root\".\n\nThis foreshadows how we'll make our frameworks work with web components.\nWe normally \"attach\" frameworks to a DOM element, and let the framework take over all descendants of that element.\nWith web components, we can attach the framework to the shadow root, which ensures that it can only access the component's \"shadow tree\".\n\nNext, we define a custom element name for our MyComponent class:\n\nWhenever a tag with that custom element name appears on the page, the corresponding DOM node is actually an instance of MyComponent!\n\nCheck it out:\n\nThere's more to web components, but that's enough to get you through the rest of the article.\n\nScaffolding Layout\n\nThe entrypoint of our app will be a React component. Here's our humble start:\n\nWe could start adding elements here to block out the basic DOM structure, but I want to write another component for that to show how we can nest web components in the same way we nest framework components.\n\nMost frameworks support composition via nesting like normal HTML elements.\nFrom the outside, it usually looks something like this:\n\nOn the inside, there are a few ways that frameworks handle this.\nFor example, React and Solid give you access to those children as a special children prop:\n\nWith web components that use shadow DOM, we can do the same thing using the <slot> element. When the browser encounters a <slot>, it replaces it with the children of the web component.\n\n<slot> is actually more powerful than React or Solid's children.\nIf we give each slot a name attribute, a web component can have multiple <slot>s, and we can determine where each nested element goes by giving it a slot attribute matching the <slot>'s name.\n\nLet's see what this looks like in practice.\nWe'll write our layout component using Solid:\n\nThere are two parts to our Solid web component: the web component wrapper at the top, and the actual Solid component at the bottom.\n\nThe most important thing to notice about the Solid component is that we're using named <slot>s instead of the children prop.\nWhereas children is handled by Solid and would only let us nest other Solid components, <slot>s are handled by the browser itself and will let us nest any HTML element — including web components written with other frameworks!\n\nThe web component wrapper is pretty similar to the example above.\nIt creates a shadow root in the constructor, and then renders the Solid component into it in the connectedCallback method.\n\nNote that this is not a complete implementation of the web component wrapper!\nAt the very least, we'd probably want to define an attributeChangedCallback method so we can re-render the Solid component when the attributes change.\nIf you're using this in production, you should probably use a package Solid provides called Solid Element that handles all this for you.\n\nBack in our React app, we can now use our TodoLayout component:\n\nNote that we don't need to import anything from TodoLayout.jsx — we just use the custom element tag that we defined.\n\nCheck it out:\n\nThat's a React component rendering a Solid component, which takes a nested React element as a child.\n\nAdding Todos\n\nFor the todo input, we'll peel the onion back a bit further and write it with no framework at all!\n\nBetween this, the example web component and our Solid layout, you're probably noticing a pattern: attach a shadow root and then render some HTML inside it.\nWhether we hand-write the HTML or use a framework to generate it, the process is roughly the same.\n\nHere, we're using a custom event to communicate with the parent component.\nWhen the form is submitted, we dispatch an add event with the input text.\n\nEvent queues are often used to decouple communication between components of a software system.\nBrowsers lean heavily on events, and custom events in particular are an important tool in the web components toolbox — especially so because the custom element acts as a natural event bus that can be accessed from outside the web component.\n\nBefore we can continue adding components, we need to figure out how to handle our state.\nFor now, we'll just keep it in our React TodoApp component.\nAlthough we'll eventually outgrow useState, it's a perfect place to start.\n\nEach todo will have three properties: an id, a text string describing it, and a done boolean indicating whether it's been completed.\n\nWe'll keep an array of our todos in React state.\nWhen we add a todo, we'll add it to the array.\n\nThe one awkward part of this is that inputRef function.\nOur <todo-input> emits a custom add event when the form is submitted.\nUsually with React, we'd attach event listeners using props like onClick — but that only works for events that React already knows about.\nWe need to listen for add events directly.\n\nIn React Land, we use refs to directly interact with the DOM.\nWe most commonly use them with the useRef hook, but that's not the only way!\nThe ref prop is actually just a function that gets called with a DOM node.\nRather than passing a ref returned from the useRef hook to that prop, we can instead pass a function that attaches the event listener to the DOM node directly.\n\nYou might be wondering why we have to wrap the function in useCallback.\nThe answer lies in the legacy React docs on refs (and, as far as I can tell, has not been brought over to the new docs):\n\nIf the ref callback is defined as an inline function, it will get called twice during updates, first with null and then again with the DOM element. This is because a new instance of the function is created with each render, so React needs to clear the old ref and set up the new one. You can avoid this by defining the ref callback as a bound method on the class, but note that it shouldn't matter in most cases.\n\nIn this case, it does matter, since we don't want to attach the event listener again on every render.\nSo we wrap it in useCallback to ensure that we pass the same instance of the function every time.\n\nTodo Items\n\nSo far, we can add todos, but not see them.\nThe next step is writing a component to show each todo item.\nWe'll write that component with Svelte.\n\nSvelte supports custom elements out of the box.\nRather than continuing to show the same web component wrapper boilerplate every time, we'll just use that feature!\n\nHere's the code:\n\nWith Svelte, the <script> tag isn't literally rendered to the DOM — instead, that code runs when the component is instantiated.\nOur Svelte component takes three props: id, text and done.\nIt also creates a custom event dispatcher, which can dispatch events on the custom element.\n\nThe $: syntax declares a reactive block.\nIt means that whenever the values of id or done change, it will dispatch a check event with the new values.\nid probably won't change, so what this means in practice is that it'll dispatch a check event whenever we check or uncheck the todo.\n\nBack in our React component, we loop over our todos and use our new <todo-item> component.\nWe also need a couple more utility functions to remove and check todos, and another ref callback to attach the event listeners to each <todo-item>.\n\nHere's the code:\n\nNow the list actually shows all our todos! And when we add a new todo, it shows up in the list!\n\nFiltering Todos\n\nThe last feature to add is the ability to filter todos.\n\nBefore we can add that, though, we need to do a bit of refactoring.\n\nI want to show another way that web components can communicate with each other: using a shared store.\nMany of the frameworks we're using have their own store implementations, but we need a store that we can use with all of them.\nFor that reason, we'll use a library called Nano Stores.\n\nFirst, we'll make a new file called store.js with our todo state rewritten using Nano Stores:\n\nThe core logic is the same; most of the changes are just porting from the useState API to the Nano Stores API.\nWe did add two new computed stores, $done and $left, which are \"derived\" from the $todos store and return completed and incomplete todos, respectively.\nWe also added a new store, $filter, which will hold the current filter value.\n\nWe'll write our filter component with Vue.\n\nThe syntax is pretty similar to Svelte's: the <script> tag at the top is run when the component is instantiated, and the <template> tag contains the component's markup.\n\nVue doesn't make compiling a component to a custom element quite as simple as Svelte does. We need to create another file, import the Vue component and call defineCustomElement on it:\n\nBack in React Land, we'll refactor our component to use Nano Stores rather than useState, and bring in the <todo-filters> component:\n\nWe did it!\nWe now have a fully functional todo app, written with four different frameworks — React, Solid, Svelte and Vue — plus a component written in vanilla JavaScript.\n\nMoving Forward\n\nThe point of this article is not to convince you that this is a good way to write web apps.\nIt's to show that there are ways to build a web app other than writing the entire thing with a single JavaScript framework — and furthermore, that web components actually make it significantly easier to do that.\n\nYou can progressively enhance static HTML.\nYou can build rich interactive JavaScript \"islands\" that naturally communicate with hypermedia libraries like htmx.\nYou can even wrap a web component around a framework component, and use it with any other framework.\n\nWeb components drastically loosen the coupling of JavaScript frameworks by providing a common interface that all frameworks can use.\nFrom a consumer's point of view, web components are just HTML tags — it doesn't matter what goes on \"under the hood\".\n\nIf you want to play around with this yourself, I've made a CodeSandbox with our example todo app.\n\nReading List\n\nIf you're interested, here are some good articles that dive even deeper into the topic:\n\nChris Ferdinandi wrote about wrapping his own UI library Reef with a web component in Reactive Web Components and DOM Diffing.\n\nAndrico Karoulla wrote a great overview of how to write framework-agnostic components aptly titled Writing Components That Work in Any Framework.\n\nThomas Wilburn showed how to use web components to build \"languages\" within HTML in Chiaroscuro, or Expressive Trees in Web Components.\n\nMaxi Ferreira wrote a wonderful article called Sharing State with Islands Architecture that goes into detail more about custom events and stores.\n\nThe official Astro documentation has a page on sharing state between islands using Nano Stores.\n\nAlthough it doesn't explicitly mention web components, the htmx essay on hypermedia-friendly scripting brings up events and islands as ways for client-side scripting to interact with hypermedia-driven web applications.",
  "title": "Web Components Eliminate JavaScript Framework Lock-in"
}