Skip to content

[reconciler] SimpleMemoComponent behind a new lazy wrapper remounts and loses state when lazy identity changes #38441

Backlog

Description

@Tortleya

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

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

Actual 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

  1. When a React.memo(Fn) wrapping a plain function component without a custom comparator (isSimpleFunctionComponent(type) && Component.compare === null at ReactFiberBeginWork.js#L479) mounts, updateMemoComponent upgrades the fiber to SimpleMemoComponent and overwrites workInProgress.type with the inner function (resolvedType) at #L487-L488, while workInProgress.elementType remains the original lazy wrapper.
  2. During reconciliation, both updateElement (#L598) and reconcileSingleElement (#L1733) compare distinct lazy wrappers via resolveLazy(elementType) === current.type (or child.type).
  3. Because resolveLazy(Lazy2) returns the REACT_MEMO_TYPE wrapper object (MemoDefault) while current.type was overwritten to the inner function (Base), MemoDefault === Base can never succeed, causing React to tear down and remount the fiber.
  4. Scope note: this is specific to React.memo() of plain function components without a custom comparator; React.memo(Fn, customCompare), class components, and forwardRef stay as MemoComponent (preserving current.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.type would also match across two separate React.memo(Base) calls (which remount when rendered directly). Comparing resolved REACT_MEMO_TYPE wrapper identity (e.g., against the resolved current.elementType when current.elementType is lazy or non-lazy) preserves exact === semantics without widening.
  • __DEV__ hot reloading: isCompatibleFamilyForHotReloading runs before the lazy clause in both functions, and SimpleMemoComponent stores resolveTypeForHotReloading(type) on workInProgress.type in __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

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions