What You'll Learn
- 1Define ownership of a DOM node so React and a library never fight over it
- 2Build a wrapper that initialises once, updates incrementally and destroys cleanly
- 3Decide what to migrate first using a strangler approach instead of a rewrite
- 4Spot double-initialisation and stale-option bugs before they reach production
Most React applications are not greenfield. They sit next to a charting library that expects a canvas and an options object, a jQuery plugin that attaches behaviour to a table, a date picker written before hooks existed, and a marketing site maintained by a team that will never learn React. The integration layer between these worlds is where subtle bugs live: a widget initialises twice and shows two tooltips, a re-render recreates a chart and loses the user's zoom, or an unmount leaves an interval running against a node React has already removed. The pattern that prevents all three is the same regardless of which library is involved â React owns the element and its lifecycle, the library owns behaviour on that element, and one component mediates.
Who owns the node
Write the contract down before the code. React creates the element and decides whether it exists at all; the library may transform its contents, attach listeners and mutate inline styles, but it must never replace the node or its parents. Anything the library owns is destroyed in the effect cleanup, and anything that must survive a re-render is stored in a ref rather than derived from props during render.
This is why the initialisation effect should run once per mount and update effects should never re-run it. A library that is expensive to create or that carries internal state â a chart with a zoom level, a table with a sort order, a map with a viewport â must be told about changes through an update method, not recreated. Recreating it on every option change is the single most common integration bug, and it presents as flicker, lost interaction state and a slow interface rather than as an error.
import { useEffect, useRef } from 'react';
import { Chart } from 'chart.js';
export function RevenueChart({ labels, datasets, options }) {
const canvasRef = useRef(null);
const chartRef = useRef(null);
useEffect(() => {
const context = canvasRef.current.getContext('2d');
chartRef.current = new Chart(context, {
type: 'line',
data: { labels, datasets },
options,
});
return () => {
chartRef.current.destroy();
chartRef.current = null;
};
}, []);
useEffect(() => {
const chart = chartRef.current;
if (!chart) return;
chart.data.labels = labels;
chart.data.datasets = datasets;
chart.update('none');
}, [labels, datasets]);
useEffect(() => {
const chart = chartRef.current;
if (!chart) return;
chart.options = options;
chart.update('none');
}, [options]);
return <canvas ref={canvasRef} role="img" aria-label="Monthly revenue" />;
}
The empty dependency array on the first effect is a statement that the widget is created once for this element's lifetime. The second effect uses update with no animation, because animating a data refresh on every parent render looks like jitter and costs frames. When callers pass a new object on every render, both update effects fire constantly â the fix belongs at the call site with memoisation, or inside the wrapper by comparing the fields you actually care about rather than object identity.
Props down, events up, and the awkward middle
A wrapper translates between two vocabularies. React props are declarative and describe what should be true; library options are imperative and describe what to do. The mapping is not always one to one, and being explicit about it prevents the class of bugs where a prop silently does nothing.
| React side | Wrapper responsibility | Failure mode when skipped |
|---|---|---|
| Primitive prop | Set through the library's update method | Value ignored after first render |
| Object or array prop | Compare fields, then update | Rebuilds on every parent render |
| Callback prop | Register once, call through a ref | Listeners stack and fire twice |
| Children or slot | Render outside the library's subtree | Library wipes React-managed nodes |
| Style or class | Keep on the wrapper element | Library sets inline styles React then fights |
| Ref | Expose a small imperative handle | Callers reach into the library directly |
The callback row is worth pausing on. Registering a listener in an effect that depends on the callback means it is torn down and recreated whenever the parent re-renders, and some libraries duplicate their internal listeners on each registration. The pattern that survives is to keep the latest callback in a ref and register a stable trampoline once; the trampoline reads the ref, so the handler is always current without ever being re-registered.
Migrating with a strangler instead of a rewrite
Rewrites of the page that owns the revenue fail for reasons that have nothing to do with code. The old markup is entangled with the old behaviour, the owner of the business rules left the company, and the effort is invisible to users until the day it ships. The strangler approach wraps the new thing around the old one: identify one leaf region, render a React island into a container the legacy code ignores, and move responsibility outward one boundary at a time.
import { StrictMode } from 'react';
import { createRoot } from 'react-dom/client';
export function mountIsland(container, Component) {
const root = createRoot(container);
return {
render(props) {
root.render(
<StrictMode>
<Component {...props} />
</StrictMode>
);
},
unmount() {
root.unmount();
},
};
}
// Legacy side: the old page keeps working around the island
const filters = mountIsland(document.getElementById('filters'), FilterPanel);
filters.render({ value: currentFilters, onChange: applyFilters });
window.addEventListener('filters:changed', (event) => filters.render(event.detail));
// Called when the legacy page itself is torn down
filters.unmount();
Choosing the first island matters more than the technique. Pick a region with a clear input and output, no direct reads of global legacy state, and a team that can own it afterwards â a filter bar or a summary card beats the checkout form. Each migration should shrink the surface where both worlds run at once, and the project is finished when the legacy code is a thin shell that only boots the application.
The jQuery specifics
jQuery integration has a few extra hazards. Plugins frequently attach handlers to document or window and never remove them, so unmounting the wrapper leaves listeners that fire against detached nodes. They also assume their element contains only their own markup, which conflicts with React rendering children into the same node; the safe rule is that React never renders children into an element a plugin manages. Where the plugin needs content, generate it as a string and let the plugin own that subtree entirely, or render the content in a sibling and let the plugin read from it.
Options objects mutate in place inside most plugins, so passing the same object you also store in state invites a plugin to rewrite your state. Always pass a fresh object built from props. And if the plugin has a destroy method, call it in cleanup â plugins that allocate intervals, observers or drag listeners are the ones that keep running after the route changes.
Double initialisation and effect churn
Two symptoms share one cause. Two tooltips stacked on a single trigger means the effect ran twice without cleanup, which in development is often Strict Mode telling you the truth about a missing dependency or a missing teardown. A widget that resets on every keystroke in an unrelated input means the initialisation effect depends on values it should only read once.
The debugging sequence is short: log mount and unmount for the wrapper, check whether cleanup runs, check the dependency array against the values the effect actually reads, and confirm the library exposes an update method rather than only a constructor. If it exposes only a constructor, wrap it in a small adapter that tears down and rebuilds, and make that cost explicit in the component so nobody multiplies it by rendering the widget inside a list.
Boundaries, bundles and the exit plan
Each wrapper is a module boundary, and boundaries are what make the migration reversible. Export a small React-shaped API, keep the library's types and quirks inside, and never let a chart.js or jQuery type escape into feature code. That lets you replace the underlying library later by editing one file, which is the actual payoff of the pattern.
Mind the bundle while you are there. A widget used on one route should be imported dynamically so its code is not in the initial payload, and a wrapper around a jQuery plugin should not drag the entire library into an application that already ships React and its framework. Finally, document the exit: which component wraps which library, what the replacement would be, and which feature still depends on it. Integration code without an owner and without an exit plan becomes the legacy you were trying to escape.
Common Mistakes
Recreating the library whenever any prop changes and losing its internal state
Fix: Initialise once and route changes through a dedicated update method
Registering callbacks in an effect that depends on them so listeners stack
Fix: Keep the latest callback in a ref behind a stable trampoline registered once
Letting a plugin manage a node React also renders children into
Fix: Give the plugin exclusive ownership of its subtree and keep React out of it
Migrating the most entangled screen first because it delivers the most value
Fix: Start with a leaf region that has clear inputs and outputs and a team to own it
Best Practices
- State the ownership contract in the wrapper: React owns the node, the library owns behaviour
- Store the library instance in a ref and expose only a narrow imperative handle
- Compare the fields you care about instead of object identity when updating
- Dynamic-import wrappers so a route's widget is not in the initial bundle
- Record every wrapper with its owner and its replacement plan
Key Takeaways
- Initialise once, update incrementally, destroy in cleanup â the same three rules for any imperative library
- Callback props need ref-backed trampolines so listeners are registered exactly once
- Strangler migration beats rewrite: wrap a leaf region and move the boundary outward
- Plugin-owned subtrees must never contain React-rendered children
- Module boundaries around integrations are what make them replaceable later