Integrate imperative widgets with cleanup
Give imperative code a dedicated DOM boundary
A vanilla widget may expose methods instead of React props. Integrate it through a narrow adapter: React controls the host element, and the widget controls only the contents it creates inside that host. Create the widget after the host exists, update it when its inputs change and destroy it when the host is removed. Avoid running widget constructors during render: rendering can be repeated or abandoned. This local gauge uses no third-party library, network requests or global DOM queries.
export function mountGauge(host) { const output = host.ownerDocument.createElement('span'); host.append(output); let disposed = false; function setValue(value) { if (disposed) throw new Error('Gauge disposed'); if (!Number.isInteger(value) || value < 0 || value > 100) { throw new RangeError('Expected an integer from 0 to 100'); } output.textContent = `Capacity: ${value}%`; } setValue(0); return { setValue, destroy() { if (disposed) return; disposed = true; output.remove(); }, };}mountGauge appends one span, writes text using textContent and returns a small API. Calling setValue(73) displays Capacity: 73%. Invalid values are rejected and destruction removes only the owned span. The function assumes the host is a dedicated element and the caller owns its lifecycle. The widget has no timers or listeners; for a widget that adds these, destroy must cancel them as well. It is intentionally not an interactive chart.
Connect lifecycle and input updates separately
import React, {useEffect, useRef} from 'react';import {mountGauge} from './gauge.mjs';type GaugeHandle = {setValue(value: number): void; destroy(): void};export function Gauge({value}: {value: number}) { const host = useRef<HTMLDivElement>(null); const handle = useRef<GaugeHandle | null>(null); const valid = Number.isInteger(value) && value >= 0 && value <= 100; useEffect(() => { if (!host.current) return; const instance = mountGauge(host.current); handle.current = instance; return () => {handle.current = null; instance.destroy();}; }, []); useEffect(() => { if (valid) handle.current?.setValue(value); }, [value, valid]); return <section><div ref={host} hidden={!valid} /> {!valid && <p role="alert">Capacity must be an integer from 0 to 100.</p>}</section>;}The first Effect creates one widget for the mounted host and supplies a matching cleanup. The second runs after setup and synchronizes valid values. Invalid input hides the previous value and displays an error. When valid input returns the same instance is updated. On unmount the handle is cleared and the owned node removed. In development StrictMode, setup-cleanup-setup must be safe; do not guard away the second setup using a persistent flag. Effects do not run during server rendering, so the valid gauge host is initially empty in server output. A static text equivalent may be preferable when server-rendered information is essential. The TypeScript interface documents the intended handle, not a runtime guarantee; the companion declaration must match the JS implementation.
Keep interactive controls under React ownership
import React, {useState} from 'react';import {Gauge} from './Gauge';export default function CapacityDemo() { const [value, setValue] = useState(40); const [visible, setVisible] = useState(true); return <section><label>Capacity <input type="range" min={0} max={100} value={value} onChange={event => setValue(Number(event.currentTarget.value))} /></label> <button type="button" onClick={() => setVisible(v => !v)}>{visible ? 'Hide gauge' : 'Show gauge'}</button> {visible && <Gauge value={value} />}</section>;}Move the slider to 73: the widget should show Capacity: 73%. Hide and show the gauge: the newly created widget should reflect 73, not duplicate output. The toggle remains mounted and retains focus during activation. A real external widget that owns interactive controls needs an explicit keyboard and focus contract, including what happens if its focused node is removed. Never replace React-owned siblings or inject untrusted HTML. If an external widget emits changes, subscribe in an Effect, unsubscribe on cleanup and define which side owns the authoritative value to avoid feedback loops. Test the adapter under StrictMode, rapid updates, unmount and remount; the provided Node tests only exercise a fake host, not React or an actual DOM.