Repository navigation
Description
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);
});
}
})();
JSActual output
React.memo(Base) => { text: 'v2:0', sameDOM: false }
React.memo(Base, customCompare) => { text: 'v2:1', sameDOM: true }
Base (no memo) => { text: 'v2:1', sameDOM: true }
Expected behavior
Because both updateElement and reconcileSingleElement explicitly implement a resolved-type fallback so distinct REACT_LAZY_TYPE wrappers resolving to the same component reuse the existing fiber, all three cases should behave consistently and output { text: 'v2:1', sameDOM: true }.
This can also affect React Server Components refreshes where Flight materializes a new lazy client-reference wrapper per response that resolves to the same React.memo(...) Client Component export.
Root cause
- When a
React.memo(Fn)wrapping a plain function component without a custom comparator (isSimpleFunctionComponent(type) && Component.compare === nullatReactFiberBeginWork.js#L479) mounts,updateMemoComponentupgrades the fiber toSimpleMemoComponentand overwritesworkInProgress.typewith the inner function (resolvedType) at#L487-L488, whileworkInProgress.elementTyperemains the original lazy wrapper. - During reconciliation, both
updateElement(#L598) andreconcileSingleElement(#L1733) compare distinct lazy wrappers viaresolveLazy(elementType) === current.type(orchild.type). - Because
resolveLazy(Lazy2)returns theREACT_MEMO_TYPEwrapper object (MemoDefault) whilecurrent.typewas overwritten to the inner function (Base),MemoDefault === Basecan never succeed, causing React to tear down and remount the fiber. - Scope note: this is specific to
React.memo()of plain function components without a custom comparator;React.memo(Fn, customCompare), class components, andforwardRefstay asMemoComponent(preservingcurrent.type === MemoWrapper) and reconcile normally.
Suggested fix
Preserve exact memo-wrapper identity matching when reconciling a REACT_LAZY_TYPE element against an existing SimpleMemoComponent fiber (in both updateElement and reconcileSingleElement).
Note two subtleties when implementing the fix:
- Distinct memo objects: Simply checking
resolved.$$typeof === REACT_MEMO_TYPE && resolved.compare === null && resolved.type === current.typewould also match across two separateReact.memo(Base)calls (which remount when rendered directly). Comparing resolvedREACT_MEMO_TYPEwrapper identity (e.g., against the resolvedcurrent.elementTypewhencurrent.elementTypeis lazy or non-lazy) preserves exact===semantics without widening. __DEV__hot reloading:isCompatibleFamilyForHotReloadingruns before the lazy clause in both functions, andSimpleMemoComponentstoresresolveTypeForHotReloading(type)onworkInProgress.typein__DEV__, so any fix should stay aligned with hot-reload resolution.
Adding a regression test comparing default React.memo(Fn) against React.memo(Fn, compare) and plain Fn across distinct lazy wrappers will lock in the parity.
Activity