[reconciler] SimpleMemoComponent behind a new lazy wrapper remounts and loses state when lazy identity changes#38441
Summary
React's reconciler intentionally reconciles distinct React.lazy wrappers by their resolved component type (// Lazy types should reconcile their resolved type in ReactChildFiber.js), so swapping to a new React.lazy wrapper that resolves to the same component preserves state and DOM identity for plain function components and React.memo(Component, customCompare).
However, default React.memo(Component) wrapping a plain function component (without a custom comparison function) is the lone inconsistent exception: when a subsequent render supplies a new React.lazy wrapper resolving to the exact same React.memo(Component) object, React unmounts and remounts it — wiping local state, recreating its DOM nodes, and re-running mount/cleanup effects.
Affected version
[email protected],[email protected](reproduced identically on Node.jsv22.22.2andv24.22.1+[email protected])- Verified unchanged on
mainatedae846a9a17442c00429f2b15375afbfa0376c9
Reproduction
In an empty directory:
npm install [email protected] [email protected] [email protected]
node <<'JS'
const {JSDOM} = require('jsdom');
const dom = new JSDOM('<!doctype html><div id="root"></div>');
global.window = dom.window;
global.document = dom.window.document;
global.IS_REACT_ACT_ENVIRONMENT = true;
const React = require('react');
const {createRoot} = require('react-dom/client');
const {act, Suspense, startTransition} = React;
function Base({label, id}) {
const [n, setN] = React.useState(0);
return React.createElement(
'button',
{id, onClick: () => setN(x => x + 1)},
`${label}:${n}`,
);
}
const MemoDefault = React.memo(Base);
const MemoCustom = React.memo(Base, (a, b) => a.label === b.label);
(async () => {
const root = createRoot(document.getElementById('root'));
for (const [name, Comp] of [
['React.memo(Base)', MemoDefault],
['React.memo(Base, customCompare)', MemoCustom],
['Base (no memo)', Base],
]) {
const Lazy1 = React.lazy(() => Promise.resolve({default: Comp}));
const Lazy2 = React.lazy(() => Promise.resolve({default: Comp}));
await act(async () => {
root.render(
React.createElement(
Suspense,
{fallback: 'loading'},
React.createElement(Lazy1, {label: 'v1', id: 'b'}),
),
);
});
const before = document.getElementById('b');
await act(async () => {
before.click();
});
await act(async () => {
startTransition(() => {
root.render(
React.createElement(
Suspense,
{fallback: 'loading'},
React.createElement(Lazy2, {label: 'v2', id: 'b'}),
),
);
});
});
const after = document.getElementById('b');
console.log(name, '=>', {text: after.textContent, sameDOM: before === after});
await act(async () => {
root.render(null);
});
}
})();
JS