React Loves Web Components (Mostly)

React Loves Web Components (Mostly)

Guillaume Pierson
• 23 min read

For years, React was the mainstream framework that got along worst with web components. Custom Elements Everywhere, a test suite that scores frameworks on how well they handle custom elements, had it near the bottom of the list. Design-system teams kept piles of wrapper components, and the standard advice was “just don’t.”

That advice gets in the way of shared components. Web components are the browser’s built-in way to write a component once and use it in every app, whatever its framework. A design system shared by React, Vue and Angular teams is the typical case. Vendor widgets like video players and maps are another, and so are migrations, where an old stack and a new one live side by side.

React 19 shipped full custom element support, and the score jumped to 100%. During a company hackday, I wanted to know whether that’s enough to ship shared components, like a design system, as web components for React apps. A test score can’t answer that, so I built an instrumented lab. It has custom elements that log every lifecycle callback with a timestamp, and a video player to probe stability. Every component also has a pure-React twin as a control group. Then I stress-tested the interop until it confessed, across nine experiments in Chrome and Firefox.

TL;DR: Yes, you can ship a design system as web components for React 19 apps. Props, re-renders and packaging held up. But custom events, load order and server-side rendering need care.

What Works

Props Finally Make Sense

A web component is a class that extends HTMLElement, registered under a tag name. Here’s my media player, trimmed:

class MediaPlayer extends HTMLElement {
static observedAttributes = ["src", "video-title"]; // watched attributes
#video = document.createElement("video");
get volume() {
return this.#video.volume; // a real property
}
set volume(v) {
this.#video.volume = v;
}
}
customElements.define("media-player", MediaPlayer);

React 19 passes props with one rule, and I confirmed it holds even for objects. If the property exists on the element, React assigns the property. Otherwise, it sets the attribute.

<media-player
src={videoUrl} // no `src` property on the class → attribute
video-title="Demo" // no property → attribute
volume={0.5} // `volume` getter/setter exists → property assignment
/>

My player logs every attribute change and property assignment. The first two props arrive through attributeChangedCallback, and the third calls the volume setter. Objects go through the property path intact, so no more [object Object] attributes. That only works if the element is defined before React renders it (more on that below).

Attributes vs. properties: An attribute belongs to the HTML markup, as in <media-player video-title="Demo">. Its value is always a string, and the element only hears about changes to the attributes listed in observedAttributes, through attributeChangedCallback. A property is a JavaScript field on the element object, as in player.volume = 0.5. It can hold any value (a number, an object, a function) and usually goes through a setter. Native elements often link the two, but on a custom element, nothing connects them unless the author writes that code. That’s why React has to pick one.

Two traps survive. First, title already exists on every HTML element, so a title prop sets the native tooltip: all my benchmark cards grew one. The same happens with any property an HTML element already has, such as id, hidden, lang, dir, slot, inert or translate. Keep those names for their native meaning.

Second, React compares non-primitive props by reference only. An inline object literal re-runs the property setter on every parent render, even when its contents are identical. If your setter does real work, memoize the value, or let the React Compiler do it for you (see below).

The lab's event log: attributes and properties arrive through different callbacks

My lifecycle probe logs the same way as the player, newest entry first. Above, label and value arrive through attributeChangedCallback and objectProp through its property setter. Changing only label re-set objectProp too, which is the second trap.

Shipping a Design System as Web Components

I packaged the player once, the way a design-system team would ship its components. The package uses Vite library mode, declaration files, and a second entry point in package.json for React:

{
"exports": {
".": { "types": "./dist/index.d.ts", "import": "./dist/index.js" },
"./react": { "types": "./dist/react.d.ts", "import": "./dist/react.js" }
}
}

./react holds no code, only the JSX typings. React users import it once and get autocompletion and type checks on <media-player>. I then loaded the same built file from a plain <script type="module"> page and from a React 19 app, and it worked in both. Nothing in the package depends on React. A design system built this way could serve a Vue or Angular app too, although I only tested these two.

TypeScript skips excess-property checks for hyphenated JSX attributes, which leaves a hole in the typings. Mine caught volue (“Did you mean ‘volume’?”) but accepted video-titl, on TypeScript 5.9 and 7 alike. Where typos matter, prefer camelCase props backed by real properties. Document the hyphenated attributes TypeScript can’t check.

I wrote my elements by hand, extending HTMLElement. If your design system uses Lit or Stencil, some of the traps below are handled for you. For example, @lit/react’s createComponent() maps custom events to React props. And Lit’s Node build ships a minimal DOM shim, so its element modules import on the server without crashing.

Re-renders Don’t Reset Internal State

A shared component can’t choose how often the apps around it re-render. The classic fear is that constant re-renders make React reset the component’s internal state.

I mounted my media player under a stress harness that re-renders its parent 20 times per second. For 15 seconds, playback never reset, the page held 60 fps, and the log recorded zero writes to the element. Typing into the title field and dragging the volume slider produced exactly one write per change, and no reset either.

React only writes the props that changed, so the <video> inside the player is never touched. The production-grade media-chrome player went through the same re-render storm without a reset. Its frame rate only dipped to 54 to 55 fps in Chrome.

Form Controls Work With Form Actions

Much of a design system is form controls, and a custom element can be one. A form-associated element declares static formAssociated = true and hands its value to the form through ElementInternals.setFormValue(). Here’s a minimal star rating:

class StarRating extends HTMLElement {
static formAssociated = true; // the browser treats it as a form control
#internals = this.attachInternals();
#value = 0;
connectedCallback() {
this.innerHTML = [1, 2, 3, 4, 5]
.map((n) => `<button type="button" value="${n}">☆</button>`)
.join("");
this.addEventListener("click", (e) => {
if (e.target.value) this.value = e.target.value;
});
}
get value() {
return this.#value;
}
set value(v) {
this.#value = Number(v);
this.#internals.setFormValue(String(this.#value)); // ends up in FormData
this.querySelectorAll("button").forEach((button, i) => {
button.textContent = i < this.#value ? "★" : "☆";
});
}
formResetCallback() {
this.value = 0; // called by the browser when the form resets
}
}
customElements.define("star-rating", StarRating);

That element works inside a React 19 form action. Its value is in the FormData the action receives, under the element’s name. When React resets the form after the action, the element’s formResetCallback runs along with the native inputs. Both browsers behaved the same.

<form action={async (formData) => save(formData.get("rating"))}>
<star-rating name="rating" />
<button type="submit">Send</button>
</form>

Moving a Playing Video Without Stopping It

Some interfaces move a live component from one place to another. A news site docks the article’s video into a corner mini-player once you scroll past it. A video-call app moves a participant’s tile from the grid to the spotlight. A dashboard opens a map widget in a full-screen modal, then puts it back in its card. Each time, the component must keep its state: playback position, camera stream, zoom level.

React can’t do that on its own, because it never moves a DOM node from one parent to another. Render a component into a different container and React destroys it and builds a new one, so a video restarts from zero. That’s true for plain React components and web components alike.

Moving the node by hand works, though:

otherContainer.appendChild(playerElement); // playerElement comes from a ref

In the video, the web component’s clock keeps counting while the player moves to the right panel and back. Its reset counter stays at 0. The React twin in the left panel isn’t playing in this recording.

The video keeps playing on the same element and the same <video>, with no reset, in both Chrome and Firefox. The element does see a disconnectedCallback / connectedCallback pair. But the HTML spec pauses a removed media element only if it’s still detached when the removing code has finished running. Mine is back before then, so make the move in one synchronous step.

React keeps updating the moved element’s props, too. In the video, the title typed after the move reaches the docked player. React holds a reference to the node itself and doesn’t care where it sits.

A plain React component’s root node can be moved the same way, and its video keeps playing too. But React listens for events at its root. Once the node sits outside the React root container, its onClick handlers stop firing. A web component’s own controls use native listeners and keep working wherever it goes.

Three rules keep the move safe:

  1. Put the element back where React rendered it before React reparents or remounts that part of the tree. Otherwise React removes the old wrapper and leaves the element behind, still playing next to a brand-new one. It’s worse if the moved element is itself the node React removes. React then throws a NotFoundError, and unless an error boundary catches it, the whole root unmounts.
  2. Don’t tear anything down in disconnectedCallback.
  3. Move it into a container React doesn’t render children into.

This trick enables layouts React can’t build on its own, like the video’s player docking into another panel without restarting. Both browsers I tested also support the moveBefore() method. It lets an element that defines connectedMoveCallback skip the disconnect/connect pair entirely.

Nesting React Inside a Web Component Works, With One Pattern

This happens during migrations, when an app moving between stacks ends up with React islands inside a web-component shell. It also happens when a design system component written in React ships as a web component.

Context does not cross the root boundary, by design: the inner app is a separate React root, so pass data through attributes and events. An event fired inside the shadow root reaches the host only if it’s composed: true. It travels further up only if it also has bubbles: true.

Don’t call root.unmount() synchronously in disconnectedCallback. At that point, the code usually runs inside React’s commit of the outer tree, and React warns on every removal. The pattern that worked for me defers the unmount and checks that the element wasn’t re-inserted in the meantime. It also creates a root only when there isn’t one yet:

connectedCallback() {
const shadow = this.shadowRoot ?? this.attachShadow({ mode: "open" });
if (!this.#root) this.#root = createRoot(shadow); // reuse after a fast move
this.#render();
}
disconnectedCallback() {
queueMicrotask(() => {
// re-inserted before this microtask ran? keep the root
if (!this.isConnected) {
this.#root?.unmount();
this.#root = null;
}
});
}

This pattern keeps the inner app alive when the same element is disconnected and put back in one task. That happens when your code moves it, like the player above, or when React reorders a keyed list. In my test, the inner counter kept its value after such a move. The pattern can’t help when React itself unmounts the host, after a key change, a conditional render or a move to another parent in JSX. React then builds a new element, and the inner app starts from scratch.

The synchronous version warned on every removal. With a plain deferred unmount, a fast reconnect could create a second root on the same container. I found that race by reading the code, then closed it.

Performance: Measure Production Builds

I benchmarked the same little widget implemented twice: once in pure React, once as a shadow-DOM custom element driven by React. My first runs, on the dev server, said web components were faster. The dev build still says so. In Firefox, 1,000 of them mount in 53 ms against 141 ms for the React version. Then I ran it again on production builds, and the lead flipped.

React’s development build adds checks for every component it renders. The pure-React card is a component plus three DOM nodes, while the web component is a single DOM element that does its own rendering. So the development build taxed one side far more than the other.

Here are the production numbers in Chrome and Firefox, with and without the React Compiler. Each bar is how long React’s flushSync takes to render and commit, so style, layout and paint aren’t included. It’s the median of three passes, each the median of 10 runs:

Bar charts for 1,000 cards in production builds: the web component mounts slowest, full updates are close, and the compiler ties the web component on a re-render where nothing changed

Pure React mounts faster, in Firefox too (37 ms against 45 ms), and full updates are close. Web components only win when most props don’t change. React writes nothing to a custom element whose props didn’t change, but it still re-runs every React component function.

The React Compiler fixes that by caching each card’s output. On a re-render where nothing changed, it cuts React’s cost two to three times in both browsers, enough to tie the web component. In exchange, it adds a few milliseconds at mount and barely changes full updates in Chrome. Compared with uncompiled React, web components cost about 20 ms more at mount per 1,000 cards in Chrome, and 8 ms more in Firefox.

The React Compiler Helps, Except After Hydration

The React Compiler memoizes around refs, imperative calls and attribute updates on custom elements, and none of them broke. It even fixes the inline-object trap from earlier. In compiled components the object is cached, so the setter only runs when the contents change.

The one bad interaction is with server rendering. On a server-rendered element, an on* handler the compiler memoizes is never attached (see point 4 in the SSR section).

What Still Bites

Custom Events Need Their Exact Name

My first attempt at using custom events failed silently:

<media-player onPlayStateChange={handler} /> // never fires, no warning

React 19 strips on and listens for the rest of the prop name exactly as written, case included. onPlayStateChange waits for an event called PlayStateChange, while the player dispatches play-state-change. The prop that works is this one:

<media-player onplay-state-change={handler} /> // works (yes, really)

The event-log screenshot in the props section shows the same thing for my probe. A click fired the onprobe-event prop and the ref listener, and onProbeEvent never ran.

This is really annoying. If you write the components, the cheapest fix is a naming rule. Name events the way the platform does (timeupdate, loadedmetadata), so playstatechange instead of play-state-change. Then onplaystatechange works on elements React renders in the browser. It doesn’t work on server-rendered ones, because hydration skips on* props.

How React 19 turns an on* prop into an event name: it strips on and listens for the rest exactly as written, case included

JSX propReact listens forThe element dispatchesResult
onPlayStateChange"PlayStateChange""play-state-change"Fails never fires, no warning
onplay-state-change"play-state-change""play-state-change"Works fires
onplaystatechange"playstatechange""playstatechange", named like timeupdateClient only hydration doesn’t attach it

If you consume components with hyphenated or camelCase event names, or render them on the server, write a small hook once. It attaches the listener through a callback ref, which React also calls during hydration. The hook works on server-rendered elements, follows the element across remounts and always calls your latest handler:

function useCustomEvent(name, handler) {
const latest = useRef(handler);
useLayoutEffect(() => {
latest.current = handler;
});
return useCallback(
(el) => {
const listener = (e) => latest.current(e);
el.addEventListener(name, listener);
return () => el.removeEventListener(name, listener);
},
[name],
);
}
function Player() {
const [playing, setPlaying] = useState(false);
const ref = useCustomEvent("play-state-change", (e) =>
setPlaying(e.detail.playing),
);
return <media-player ref={ref} />;
}

A wrapper such as @lit/react’s createComponent does the same mapping from camelCase props to event names. Either way, event-rich APIs come with a permanent wrapper cost under React, so budget for it.

A Prop Only Writes When Its Value Changes

Pass volume={0.5} to the player, let the user drag the player’s own volume slider to 0.9, then re-render the parent. Nothing happens.

React diffs against its previous render, not against the DOM. As far as it knows, volume is still 0.5, so it writes nothing, and your “controlled” prop no longer controls anything. React only writes again when the prop’s value changes, and then it overwrites the internal 0.9. As a parting gift, the player’s own slider kept showing 0.9 afterwards: keeping the two in sync is entirely the component author’s job.

Native inputs don’t have this problem, because React special-cases them and puts the controlled value back after every input event. Custom elements get none of that, so they behave like an <input> with a defaultValue. Treat props as initial values or one-time commands, and get real state back out through events.

For the volume slider, the player web component announces every change the user makes:

// in MediaPlayer, when the user drags its own slider
this.dispatchEvent(new CustomEvent("volume-change", { detail: { volume } }));

The React side stores that value and passes it back as the prop, using the useCustomEvent hook from above:

function Player() {
const [volume, setVolume] = useState(0.5);
const ref = useCustomEvent("volume-change", (e) =>
setVolume(e.detail.volume),
);
return (
<>
<media-player ref={ref} volume={volume} />
<button onClick={() => setVolume(0.5)}>Reset volume</button>
</>
);
}

Now React’s previous render matches the element. When the user drags to 0.9, the state follows, so the reset button changes the prop from 0.9 to 0.5, and React writes it.

Define Elements Before React Renders Them

I rendered <media-player volume={0.5} config={{ autoplay: true }} /> first, and called customElements.define() only afterwards. The player played at its default volume of 1, and config="[object Object]" sat on the element as an attribute. Neither browser printed a warning.

Here’s what happened. When React renders a tag the browser doesn’t know yet, the browser still creates the element, but as a plain HTMLElement, without the volume setter. React checks for the property at that moment, doesn’t find it, and falls back to attributes: volume="0.5", and an object turned into the string "[object Object]".

When define() runs later, the browser upgrades the element: the existing node becomes a real MediaPlayer web component, setter included. But the attributes React already wrote stay as they are. My player doesn’t watch a volume attribute, so it ignores volume="0.5". And the string "[object Object]" doesn’t hold the object anymore.

React doesn’t fix this on its own, for the reason explained in the previous section: it only writes a prop when its value changes. The next time I changed volume, React found the setter and assigned the property. config never changed, so it stayed a useless string for good.

This happens whenever the element module loads after React’s first render: a lazy-loaded design-system bundle, a route-level code split, an import() in an effect. Import the elements before React renders them, for example in the app’s entry point. On the component side, read the existing attributes in connectedCallback as a fallback. That recovers strings and numbers, but not objects.

Sorting a List Disconnects Its Elements

To reorder a keyed list, React moves the existing DOM nodes. For a custom element, a move is a removal followed by an insertion, so the browser calls disconnectedCallback, then connectedCallback. A React component gets nothing of the sort: React doesn’t unmount a component it only moves.

I rendered five cards, each with an internal click counter React knows nothing about, then shuffled the list. With stable keys (key={card.id}), each counter traveled with its card. The log showed a disconnect/connect pair for every moved card, and no new constructor: the element survives, but its lifecycle runs as if it had been removed. A card that stops a video, closes a connection or clears its state in disconnectedCallback breaks on a simple sort. It’s the docking rule again: a reorder isn’t a removal, so don’t tear anything down in disconnectedCallback.

Index keys, the classic React trap, are worse with web components. React uses each item’s key to decide which existing DOM element that item gets. With key={index}, the key at position 0 stays 0 whatever the item, so React never moves anything. It only reassigns each card’s label attribute in place.

The bottom list in the video above uses key={index}. Card A was clicked once, card B twice, and so on up to card E. After the shuffle, the labels follow the same order as in the top list, but the counters still read 1 to 5, so each one now belongs to the wrong card. Removing the middle card then destroys the last element, counter 5 included. Inserting a card at the front relabels every card and creates one new element at the end.

Pure-React components with local state have the same index-key problem. But their state shows up in React DevTools, and React developers know it follows the key. A web component’s state lives in the DOM instance, where React can’t see it, and the app developer may not even know the component has any.

Server-Side Rendering Is the Hard Part

My favorite bug of the hackday came from React.lazy, which looks like a way to keep element modules off the server. Under Vite’s dev SSR, the lazy route’s import still ran on the server. A Node stack trace ended up inside the page’s HTML, which is server-side rendering, technically.

I tested React’s renderToString under Vite’s SSR dev server, not Next.js, Server Components or React’s streaming renderers. The React.lazy surprise may be specific to Vite’s dev server. The first four points below come from Node and React themselves, so expect them anywhere.

Where React 19 sends each prop of a defined <media-player> whose class has a volume property

PropClient render
createRoot()
Server render
renderToString()
Hydration
hydrateRoot()
volume={0.5} the class has a propertyWorks property el.volume = 0.5Expected attribute volume="0.5"Lost or late assigned only once the value changes; until then the video plays at 1
video-title="Demo" no such propertyWorks attribute video-titleWorks attribute video-titleWorks kept from the server HTML
config={obj} an objectWorks property el.config = objLost or late dropped, without a warningLost or late assigned only once a render passes a new object
onplaystatechange={fn} an event handlerWorks listener for the playstatechange eventExpected not in the HTMLLost or late attached only once the handler changes
ref={callback} a callback refWorks called with the elementExpected not calledWorks called with the element, so a ref can attach listeners
  1. class X extends HTMLElement crashes Node at import time. Guarding customElements.define() isn’t enough, because the extends clause itself throws ReferenceError: HTMLElement is not defined. Load element modules on the client only, in the client entry, before hydrateRoot(). My lab used an import() in an effect, which lands after the first commit. The next render ran into the load-order trap and left an objectprop="[object Object]" attribute behind.
  2. The server turns primitive props into attributes and drops the rest. Objects vanish from the HTML without a warning.
  3. Hydration assigns no properties. React adopts the server’s DOM as it is, so volume={0.5} stays a volume="0.5" attribute. My player doesn’t watch that attribute, so the <video> played at volume 1. Defining the element before hydrateRoot() doesn’t change that. I checked in both browsers, with development and production builds. React only assigns volume once its value changes, and an object prop only once a render passes a new object. A stable object, like a module constant, never arrives. Make server-rendered elements read their attributes, and pass objects after hydration (or render those elements on the client only).
  4. Hydration doesn’t attach event props either. It never calls addEventListener for an onplaystatechange prop, and a later render only attaches it if the handler changed. A stable handler, such as a useCallback or any inline arrow the React Compiler memoizes, is never attached. An uncompiled inline arrow is attached on the first re-render, and every event before that is lost. I checked it the same way, in both browsers, with and without the compiler. The useCustomEvent hook above works from the start, because React attaches refs during hydration. There’s an open React issue about it, still marked unconfirmed.
  5. Declarative Shadow DOM puts a component’s shadow content in the server HTML, so it shows before any JavaScript loads. It survives hydration on React 19.3. I injected a <template shadowrootmode="open"> through dangerouslySetInnerHTML. The browser built a real shadow root from the server HTML, 9 ms into the page’s life in Firefox. On React 19.2, the next re-render destroyed it. React compared the inline {{ __html }} object by identity and rewrote the wrapper’s innerHTML, and an innerHTML parse doesn’t create a shadow root. React 19.3 compares the string. Either way, the development build still logs a harmless hydration mismatch for the block.
const markup = `<div><template shadowrootmode="open">…</template></div>`;
// React 19.2: a new object on every render, so the next re-render
// replaces the host <div> with one that has no shadow root
<div dangerouslySetInnerHTML={{ __html: markup }} />;
// Works on 19.2 and 19.3: the same object on every render
const DSD = { __html: markup };
<div dangerouslySetInnerHTML={DSD} />;

Until the first four points are handled, I’d keep web components out of the server-rendered path and make their modules safe to import in Node.

Verdict

You can build your common components as web components and use them in React 19. In my tests, props arrived the way you’d expect, form controls worked with form actions, and neither re-renders nor the React Compiler disturbed them. One package served a React app and a plain HTML page, and performance stayed close to pure React apart from a slower mount. So React does love web components, and they deserve a better reputation. The “mostly” in the title stands for events, load order and server-side rendering, so plan for those.

I’d use web components with React 19 for:

  • shared components, like a design system used by apps on different frameworks
  • stable, self-contained widgets such as players, editors, charts and maps
  • widgets that must keep working when moved to another container
  • the boundary between two stacks during a migration

I’d keep plain React components for server-rendered pages, for components that need React context, and for components with a rich event API. That’s where you end up writing wrappers or hitting failures React doesn’t report.

For a design-system team, the wrapper cost is paid once instead of in every app. Name events the way the platform does, and ship a hook like useCustomEvent for server-rendered apps. Ship the React typings with an entry point that also registers the elements on import (my ./react entry only held the typings). Each React app then only has to import that entry point before its first render.

If you go with web components, pin this checklist next to the monitor:

  1. Give web components stable keys, and keep teardown out of disconnectedCallback: sorting a list triggers it.
  2. Name custom events like playstatechange. On server-rendered elements, or for event names you don’t control, listen through a ref and addEventListener.
  3. Treat props as one-way messages, and get state back out through events.
  4. Register elements before React first renders them.
  5. Keep element modules out of anything that runs in Node, and don’t count on hydration to set props or attach event listeners.
  6. Memoize object props, or let the React Compiler do it.
  7. Prefer property-backed camelCase props where typos matter.
  8. Benchmark production builds.

As for my lab, it leaves gaps, and you’re welcome to fill them. I didn’t test Safari, or any server setup beyond renderToString in Vite. Server rendering is where web components hurt most, so that’s where I’d look next. Lit’s @lit-labs/ssr-react, still a Labs package, renders Lit components’ shadow DOM into React’s server HTML. For Lit elements, it would replace my dangerouslySetInnerHTML workaround, though I don’t know yet whether it helps with the hydration gaps.

The lab source code is available at marmelab/react-and-web-components. It runs locally with pnpm install and pnpm dev. If you try it in Safari, open an issue with what breaks. And if the hydration bug bites you, add your case to the open React issue.

Authors

Guillaume Pierson

Full-stack web developer at marmelab, Guillaume was initially a Java guy. Fan of anime and video games, he can develop an AI that beats you every time.

Ready to build something extraordinary?
Our team of talented full-stack developers is ready to tackle your next web or mobile project. Let's build it together!