Skip to content

Block Editor: Memoize the block list lazily in InnerBlocks and BlockPreview - #86323

Open
retrofox wants to merge 4 commits into
trunkfrom
fix/block-editor-memo-circular-import
Open

retrofox wants to merge 4 commits into
trunkfrom
fix/block-editor-memo-circular-import

Conversation

@retrofox

@retrofox retrofox commented Nov 4, 2026 •

Copy link
Copy Markdown
Contributor

What?

InnerBlocks and the auto BlockPreview memoize a wrapper around the block list instead of the imported BlockListItems and BlockList bindings. BlockPreview also imports BlockList by name.

Why?

Both modules sit in an import cycle with block-list and call memo() at module scope.

In the CommonJS build that line runs before block-list/index.cjs has assigned its exports, so memo() receives undefined: loading @wordpress/block-editor/build/index.cjs logs memo: The first argument must be a component. Instead received: undefined twice, and rendering InnerBlocks or BlockPreview from that build fails.

BlockPreview has a second problem. Its default import compiles to a __toESM() copy of the block-list exports, taken while they are still empty, so BlockList stays undefined there even at render time.

The ESM build is unaffected.

This is a workaround for the Rolldown CommonJS output regression tracked in #86328. The cycle stays: block-list and inner-blocks import each other, and both sit in a 98-module cycle through the components index.

How?

The memoized component is a wrapper that renders BlockListItems or BlockList at render time. Memoization still skips re-renders on unchanged props.

block-list also exports BlockList by name and BlockPreview imports it that way, so the CommonJS build reads it from the module at render time, as it already does for BlockListItems. The package's public exports don't change.

Testing Instructions

Build, then count the warnings logged on load:

npm run build
NODE_ENV=development node -e "require( './packages/block-editor/build/index.cjs' )" 2>&1 | grep -c 'memo: The first argument must be a component'

On trunk this prints 2 (the require then stops on window is not defined, which is expected outside a browser). With this change it prints 0.

The count doesn't cover rendering. Save the script below as cjs-check.cjs in the repository root to render both components from the CommonJS build under jsdom:

NODE_ENV=development node cjs-check.cjs

On trunk both lines end in FAILS. With this change both end in renders.

cjs-check.cjs
const Module = require( 'module' );
const { JSDOM, VirtualConsole } = require( './test/unit/node_modules/jsdom' );

const { window } = new JSDOM( '', {
	url: 'http://localhost/',
	pretendToBeVisual: true,
	virtualConsole: new VirtualConsole(),
} );
for ( const key of Object.getOwnPropertyNames( window ) ) {
	if ( ! ( key in globalThis ) ) {
		globalThis[ key ] = window[ key ];
	}
}
globalThis.IS_REACT_ACT_ENVIRONMENT = true;

// jsdom measures nothing: report a width so `BlockPreview` mounts its block list.
globalThis.ResizeObserver = class {
	constructor( callback ) {
		this.callback = callback;
	}
	observe( target ) {
		const contentRect = { width: 800, height: 600 };
		queueMicrotask( () => this.callback( [ { target, contentRect } ] ) );
	}
	unobserve() {}
	disconnect() {}
};

// jsdom does not load the preview iframe: render its children in place.
const load = Module._load;
Module._load = ( request, parent, ...rest ) =>
	request === '../iframe/index.cjs' &&
	parent.filename.endsWith( 'block-preview/auto.cjs' )
		? { __esModule: true, default: ( { children } ) => children }
		: load( request, parent, ...rest );

const modules = './packages/block-editor/node_modules/';
const { createElement, act } = require( modules + 'react' );
const { createRoot } = require( modules + 'react-dom/client' );
const { registerBlockType, createBlock } = require( './packages/blocks' );
const {
	BlockEditorProvider,
	BlockList,
	BlockPreview,
	useBlockProps,
	useInnerBlocksProps,
} = require( './packages/block-editor' );

registerBlockType( 'test/group', {
	apiVersion: 3,
	title: 'Group',
	edit: () => createElement( 'div', useInnerBlocksProps( useBlockProps() ) ),
	save: () => null,
} );
registerBlockType( 'test/text', {
	apiVersion: 3,
	title: 'Text',
	edit: () => createElement( 'p', useBlockProps(), 'nested' ),
	save: () => null,
} );
const blocks = [ createBlock( 'test/group', {}, [ createBlock( 'test/text' ) ] ) ];

async function check( label, value, children ) {
	const container = document.body.appendChild( document.createElement( 'div' ) );
	const root = createRoot( container, { onUncaughtError() {} } );
	try {
		await act( async () =>
			root.render( createElement( BlockEditorProvider, { value }, children ) )
		);
		await act( () => new Promise( ( resolve ) => setTimeout( resolve, 50 ) ) );
	} catch {}
	const rendered = container.textContent.includes( 'nested' );
	console.log( `${ label }: ${ rendered ? 'renders' : 'FAILS' }` );
}

( async () => {
	await check( 'InnerBlocks', blocks, createElement( BlockList ) );
	await check( 'BlockPreview', [], createElement( BlockPreview, { blocks } ) );
	process.exit();
} )();
npm run test:unit -- packages/block-editor/src/components/inner-blocks packages/block-editor/src/components/block-preview

…review

The CommonJS build evaluates memo( BlockListItems ) and memo( BlockList ) while block-list is still loading through the circular import, so both components were undefined there. Memoizing a wrapper reads the binding at render time instead.
@retrofox
retrofox requested a review from ellatrix as a code owner November 4, 2026 17:24
@retrofox retrofox added [Type] Bug An existing feature does not function as intended [Package] Block editor /packages/block-editor labels Nov 4, 2026
@retrofox retrofox self-assigned this Nov 4, 2026
@github-actions

github-actions Bot commented Nov 4, 2026 •

Copy link
Copy Markdown

🤖 PR meta 🤖

Preview in WordPress Playground Preview in Storybook

🎉 Props

If you're merging code through a pull request on GitHub, copy and paste the following into the bottom of the merge commit message.

Co-authored-by: retrofox <retrofox@git.wordpress.org>
Co-authored-by: louwie17 <louwie17@git.wordpress.org>
Co-authored-by: jsnajdr <jsnajdr@git.wordpress.org>
Co-authored-by: simison <simison@git.wordpress.org>
Co-authored-by: anomiex <bjorsch@git.wordpress.org>

To understand the WordPress project's expectations around crediting contributors, please review the Contributor Attribution page in the Core Handbook.


Props Bot commands

You can trigger Props Bot actions by commenting on this PR:

  • @propsbot add <username> to give props to a GitHub user. Requires write access.
  • @propsbot remove <username> to leave a user out of the props. Requires write access.
  • @propsbot refresh to refresh this list. Adding the props-bot label works too.

Updated as activity occurs, without notifying anyone named here. Add the props-bot label to refresh.

📦 Bundle size

Size Change: +17 B (0%)

Total Size: 8.61 MB

📦 View Changed
Filename Size Change
build/scripts/block-editor/index.min.js 545 kB +17 B (0%)

254f0b2 Run

⚡ Performance

Show the results

Client side metrics exclude the server response time.

front-end-block-theme

Metric 40a2cdb trunk % Change
timeToFirstByte 49.55 ms +6.56% -2.72% 51.35 ms +4.77% -3.89% -3.51%
largestContentfulPaint 88 ms +4.55% -6.82% 88 ms +4.55% -4.55% 0%
lcpMinusTtfb 35.5 ms +18.59% -8.87% 34.65 ms +18.61% -4.04% 2.45%
wpBeforeTemplate 25.01 ms +11% -1.4% 25.32 ms +5.09% -3.28% -1.22%
wpTemplate 20.67 ms +1.74% -3.73% 21.14 ms +5.06% -6.15% -2.22%
wpTotal 45.64 ms +7.34% -2.74% 47.32 ms +5.11% -4.44% -3.55%
wpMemoryUsage 7.72 MB +0% -0% 7.68 MB +0% -0% 0.43%
wpDbQueries 16 +0% -0% 16 +0% -0% 0%

front-end-classic-theme

Metric 40a2cdb trunk % Change
timeToFirstByte 42.55 ms +3.64% -4.47% 41.5 ms +7.11% -2.17% 2.53%
largestContentfulPaint 96 ms +0% -4.17% 94 ms +2.13% -2.13% 2.13%
lcpMinusTtfb 53.2 ms +2.63% -3.38% 51.55 ms +5.33% -1.65% 3.2%
wpBeforeTemplate 22.49 ms +4.22% -2.71% 22.01 ms +6.59% -1.09% 2.18%
wpTemplate 16.45 ms +3.22% -4.74% 15.68 ms +6.7% -2.61% 4.91%
wpTotal 39.07 ms +4.4% -4.43% 38.04 ms +7.54% -2.26% 2.71%
wpMemoryUsage 6.41 MB +0% -0% 6.37 MB +0% -0% 0.53%
wpDbQueries 13 +0% -0% 13 +0% -0% 0%

media-processing

Metric 40a2cdb trunk % Change
mediaProcessingJpeg 404.13 ms +0.55% -0.58% 399.32 ms +1.11% -0.24% 1.2%
mediaProcessingAvif 5851.85 ms +0.32% -0.15% 5883.58 ms +0.24% -0.33% -0.54%
mediaProcessingJpegToAvif 4003.44 ms +0.19% -0.18% 4009.49 ms +0.13% -0.1% -0.15%

media-upload

Metric 40a2cdb trunk % Change
jpegUploadProcessing 1500.03 ms +30.45% -2.44% 1472.59 ms +1.97% -0.53% 1.86%
pngUploadProcessing 244.45 ms +2.51% -4.9% 252.85 ms +1.02% -2.74% -3.32%
largeJpegUploadProcessing 1469.09 ms +0.74% -0.39% 1464.74 ms +0.12% -0.4% 0.3%
multipleImageUploadProcessing 2040.28 ms +1.66% -22.67% 2060.61 ms +0.81% -0.83% -0.99%

post-editor

Metric 40a2cdb trunk % Change
serverResponse 266.63 ms +3.07% -7.83% 260.11 ms +3.52% -7.92% 2.51%
firstPaint 238.77 ms +41.29% -13.51% 222.05 ms +39.57% -17.43% 7.53%
domContentLoaded 570.29 ms +4.23% -1.26% 552.89 ms +5.08% -0.74% 3.15%
loaded 571 ms +4.25% -1.24% 553.55 ms +5.07% -0.73% 3.15%
firstContentfulPaint 338.99 ms +1.69% -0.48% 335.31 ms +6.46% -4.75% 1.1%
firstBlock 1465.76 ms +5.97% -1.02% 1409.76 ms +1.42% -2.02% 3.97%
type 13.02 ms +2.61% -6.45% 12.17 ms +1.73% -0.66% 6.98%
typeWithoutInspector 12.41 ms +3.55% -9.83% 12.27 ms +3.42% -5.54% 1.14%
typeWithTopToolbar 15.52 ms +3.99% -10.5% 16.52 ms +7.45% -7.26% -6.05%
typeContainer 6.09 ms +11.66% -2.46% 6.25 ms +4.32% -15.04% -2.56%
focus 76.31 ms +6.77% -2.71% 72.9 ms +3.48% -3.79% 4.68%
firstFocus 152.87 ms +0% -0% 156.6 ms +0% -0% -2.38%
selectAll 244.54 ms +1.17% -1.69% 227.74 ms +3.1% -1.15% 7.38%
undo 20.76 ms +9.1% -4.62% 21.73 ms +8.1% -8.88% -4.46%
listViewOpen 48.95 ms +12.26% -4.74% 47.22 ms +3.16% -8.17% 3.66%
inserterOpen 27.43 ms +5.87% -4.37% 26.3 ms +1.63% -1.71% 4.3%
inserterHover 8.02 ms +11.97% -2.62% 8.54 ms +4.8% -7.38% -6.09%
inserterSearch 6.22 ms +13.5% -3.22% 6.33 ms +6.48% -3.95% -1.74%
loadPatterns 412.61 ms +3.33% -3.34% 431.88 ms +4.76% -4.03% -4.46%
wpTotal 259.24 ms +3.1% -8.03% 253.25 ms +3.24% -8.17% 2.37%
wpMemoryUsage 14.76 MB +0% -0% 14.73 MB +0% -0% 0.24%
wpDbQueries 55 +0% -0% 55 +0% -0% 0%

site-editor

Metric 40a2cdb trunk % Change
serverResponse 446.47 ms +7.71% -0.56% 479.96 ms +1.08% -7.59% -6.98%
firstPaint 398.12 ms +7.24% -7.23% 360.15 ms +11.12% -11.17% 10.54%
domContentLoaded 907.79 ms +5.46% -1.08% 872.84 ms +2.96% -1.1% 4%
loaded 908.96 ms +5.43% -1.07% 873.84 ms +3% -1.11% 4.02%
firstContentfulPaint 520.8 ms +7.92% -0.74% 504.94 ms +1.82% -1.33% 3.14%
firstBlock 2664.05 ms +0.45% -0.81% 2576.74 ms +0.57% -0.52% 3.39%
type 19.65 ms +2.19% -9.21% 18.92 ms +5.13% -12.32% 3.86%
navigate 120.82 ms +5.31% -2.51% 123.75 ms +3.2% -7.56% -2.37%
loadPatterns 1451.82 ms +3.03% -7.86% 1408.51 ms +6.09% -5.62% 3.07%
loadPages 1020.72 ms +4.75% -4.28% 1033.6 ms +2.75% -2.47% -1.25%
wpTotal 436.93 ms +7.83% -0.59% 470.47 ms +1.06% -7.78% -7.13%
wpMemoryUsage 12.78 MB +0% -0% 12.74 MB +0% -0% 0.27%
wpDbQueries 45 +0% -0% 45 +0% -0% 0%

254f0b2 Run

🏁 Flaky tests

Some tests passed with failed attempts. The failures may not be related to this commit but are still reported for visibility. See the documentation for more information.

Undo restores the post selection when another synced entity is loaded (RTC WebSocket) in /test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts, passed after 1 failed attempt.
Error: expect(received).toMatchObject(expected)

- Expected  - 2
+ Received  + 2

  Object {
    "attributeKey": "content",
    "blockIndex": 0,
    "content": "abcdef",
-   "endOffset": 3,
-   "offset": 3,
+   "endOffset": 6,
+   "offset": 6,
  }

Call Log:
- Timeout 5000ms exceeded while waiting on the predicate
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts:363:5
Undo restores the post selection when another synced entity is loaded in /test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts, passed after 1 failed attempt.
Error: expect(received).toMatchObject(expected)

- Expected  - 2
+ Received  + 2

  Object {
    "attributeKey": "content",
    "blockIndex": 0,
    "content": "abcdef",
-   "endOffset": 3,
-   "offset": 3,
+   "endOffset": 4,
+   "offset": 4,
  }

Call Log:
- Timeout 5000ms exceeded while waiting on the predicate
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/collaboration-undo-redo.spec.ts:363:5
does not select blocks in the canvas preview when editing from the sidebar (Site Editor v2) in /test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeFocused() failed

Locator: getByRole('combobox', { name: 'Search or type URL' })
Expected: focused
Timeout: 5000ms
Error: element(s) not found

Call log:
  - Expect "toBeFocused" getByRole('combobox', { name: 'Search or type URL' }) with timeout 5000ms
  - waiting for getByRole('combobox', { name: 'Search or type URL' })

    at LinkControl.useLinkControlSearch (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:416:47)
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/navigation-sidebar-list-view.spec.js:179:21
inserts a block should show a blue line indicator in /test/e2e/specs/editor/various/inserting-blocks.spec.js, passed after 1 failed attempt.
TypeError: Cannot read properties of null (reading 'y')
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/various/inserting-blocks.spec.js:681:32
persists Copy and Images guidelines across a refresh in /test/e2e/specs/admin/guidelines.spec.js, passed after 1 failed attempt.
Error: expect(locator).toHaveValue(expected) failed

Locator:  getByRole('listitem').filter({ has: getByRole('button', { name: 'Images', exact: true }) }).getByRole('textbox', { name: 'Images guidelines' })
Expected: "Always include descriptive alt text."
Received: ""
Timeout:  5000ms

Call log:
  - Expect "toHaveValue" getByRole('listitem').filter({ has: getByRole('button', { name: 'Images', exact: true }) }).getByRole('textbox', { name: 'Images guidelines' }) with timeout 5000ms
  - waiting for getByRole('listitem').filter({ has: getByRole('button', { name: 'Images', exact: true }) }).getByRole('textbox', { name: 'Images guidelines' })
    14 × locator resolved to <textarea rows="4" id="base-ui-_r_f_" aria-labelledby="base-ui-_r_g_" class="_980b3b4776ac8f81__textarea e399341d589660ad__textarea _5b33aa2d48624b4f__input _9edfcd97eeaee9dc__input"></textarea>
       - unexpected value ""

    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/admin/guidelines.spec.js:290:5
should partially select with shift + click in /test/e2e/specs/editor/various/multi-block-selection.spec.js, passed after 1 failed attempt.
Error: expect(received).toMatchObject(expected)

- Expected  -  1
+ Received  + 11

  Array [
    Object {
      "attributes": Object {
-       "content": "<strong>1</strong>|2",
+       "content": "<strong>1</strong>[",
+       "dropCap": false,
+     },
+     "innerBlocks": Array [],
+     "name": "core/paragraph",
+   },
+   Object {
+     "attributes": Object {
+       "content": "]2",
+       "dropCap": false,
      },
+     "innerBlocks": Array [],
      "name": "core/paragraph",
    },
  ]

Call Log:
- Timeout 5000ms exceeded while waiting on the predicate
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/various/multi-block-selection.spec.js:1600:41
templates can be registered and edited (Site Editor v2) in /test/e2e/specs/site-editor/template-registration.spec.js, passed after 1 failed attempt.
Error: expect(locator).toBeVisible() failed

Locator: getByText('AuthorGutenberg')
Expected: visible
Error: strict mode violation: getByText('AuthorGutenberg') resolved to 3 elements:
    1) <div data-wp-c16t="true" data-wp-component="Flex" class="_463056a1846babdd__flex eefcc0383f58d3a1__items-row _8a741740b23dfb57__expanded-row components-flex dataviews-view-grid__field">…</div> aka getByRole('row', { name: 'Row 1' }).getByText('AuthorGutenberg')
    2) <div data-wp-c16t="true" data-wp-component="Flex" class="_463056a1846babdd__flex eefcc0383f58d3a1__items-row _8a741740b23dfb57__expanded-row components-flex dataviews-view-grid__field">…</div> aka locator('[id="emptytheme//page"]').getByText('AuthorGutenberg')
    3) <div data-wp-c16t="true" data-wp-component="Flex" class="_463056a1846babdd__flex eefcc0383f58d3a1__items-row _8a741740b23dfb57__expanded-row components-flex dataviews-view-grid__field">…</div> aka locator('[id="emptytheme//plugin-template"]').getByText('AuthorGutenberg')

Call log:
  - Expect "toBeVisible" getByText('AuthorGutenberg') with timeout 5000ms
  - waiting for getByText('AuthorGutenberg')

    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/site-editor/template-registration.spec.js:60:55
three users concurrently edit a large post with diverse blocks in /test/e2e/specs/editor/collaboration/collaboration-stress.spec.ts, passed after 1 failed attempt.
TimeoutError: locator.waitFor: Timeout 17500ms exceeded.
Call log:
  - waiting for getByRole('button', { name: /Collaborators list/ }) to be visible

    at map (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/fixtures/collaboration-utils.ts:193:7)
    at CollaborationUtils.waitForMutualDiscovery (/home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/fixtures/collaboration-utils.ts:188:10)
    at /home/runner/work/gutenberg/gutenberg/test/e2e/specs/editor/collaboration/collaboration-stress.spec.ts:416:28

254f0b2 Run

Co-authored-by: retrofox <77539+retrofox@users.noreply.github.com>
@retrofox
retrofox requested a review from jsnajdr November 5, 2026 09:13

@louwie17 louwie17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for picking this up. The InnerBlocks change works, but the BlockPreview one only moves the failure from module load to render time. Details are inline.

What I tested

  • Node, CommonJS build: on trunk, require( 'build/index.cjs' ) logs the memo warning twice. With this PR it logs it 0 times.
  • Node + jsdom, CommonJS build: InnerBlocks (a group with a nested paragraph) renders with this PR. Rendering BlockPreview's MemoizedBlockList still throws Element type is invalid … got: undefined.
  • Node + jsdom, CommonJS build, with the change suggested inline: MemoizedBlockList renders and the warning count stays at 0.
  • Browser (wp-env, PR build): nested blocks (Group > Columns > Paragraph) and the pattern inserter previews render, with no console errors. The browser loads the script bundle, not the .cjs files, so this only shows that the PR doesn't break the editor. It doesn't exercise the CommonJS bug.
  • npm run test:unit for inner-blocks and block-preview passes (3/3). lint:js on the changed files is clean.

Testing gap

The testing instructions count memo warnings, which can't catch this case: the warning goes away while the render still fails. A full BlockPreview render in jsdom doesn't catch it either, because AutoBlockPreview only mounts the list once the container has a measured width, and jsdom always reports 0. A smoke test that requires build/index.cjs and renders the memoized list directly (or mocks a non-zero container width) would cover it. Not blocking, but without it this could break again unnoticed.

// This is used to avoid rendering the block list if the sizes change.
const MemoizedBlockList = memo( BlockList );
// Wrapped because the circular import leaves `BlockList` undefined when the CommonJS build runs this line.
const MemoizedBlockList = memo( function MemoizedBlockListWrapper(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The lazy wrapper still reads undefined here, so BlockPreview crashes when it renders from the CommonJS build.

The difference from inner-blocks is the import style. inner-blocks uses a named import, which Rolldown compiles to a live property read (___block_list_index_tsx.BlockListItems), so by render time it finds the function. This file uses a default import, which Rolldown wraps in __toESM():

let ___block_list_index_tsx = require("../block-list/index.cjs");
___block_list_index_tsx = __toESM(___block_list_index_tsx);

__toESM copies getters only for the export names that exist at that moment. During the cycle, block-list has no exports yet, so the copy never gets default, even after block-list finishes loading. With this PR's build, after loading build/index.cjs, the copy in auto.cjs contains only __esModule, and .default is undefined. Rendering MemoizedBlockList throws:

Element type is invalid: expected a string (for built-in components) or a class/function (for composite components) but got: undefined.

I tested this fix, which switches to a named import so it compiles the same way as inner-blocks:

// block-list/index.tsx
export { BlockList };

// block-preview/auto.tsx
import { BlockList } from '../block-list';

The build then reads ___block_list_index_tsx.BlockList live, MemoizedBlockList renders, and the warning count stays at 0. The added named export is in an internal module, so the package's public API doesn't change.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You're right, thanks for digging into this. I only counted the warnings and never rendered BlockPreview from the CommonJS build.

Applied your fix.block-list exports BlockList by name and auto.tsx imports it that way.

Tested on a build of this branch under jsdom, with a mocked container width: InnerBlocks and BlockPreview both render and the warning count stays at 0. The previous commit fails on BlockPreview only, and trunk fails on both. I added the script to the testing instructions.

About the smoke test: the unit test job doesn't build the CommonJS output, so I'd leave a build-level check to #86328 rather than add one here for two components. Happy to add it here if you prefer.

The CommonJS build left the default import undefined
@jsnajdr

jsnajdr commented Nov 5, 2026

Copy link
Copy Markdown
Member

What if the MemoizedBlockList and BlockListItemsMemo components were not defined in the consumer module, but in the modules where the inner components are? Then the importer doesn't use them statically at top-level, but always inside another function.

Would that break the import cycle, too? Maybe together with making BlockList a named export? If that works, it would be more elegant.

I also see another, very long cycle:

components/block-preview/auto.tsx
  -> components/block-list/index.tsx
  -> components/block-list-appender/index.tsx
  -> components/default-block-appender/index.tsx
  -> components/inserter/index.tsx
  -> components/inserter/menu.tsx
  -> components/inserter/preview-panel.tsx
  -> components/block-preview/index.tsx
  -> components/block-preview/auto.tsx

This one is probably not dangerous at runtime, but it's still a cycle, I wonder if there is any way to break it. Block preview has a block list, it has an appender, which has inserter, and inserter has a block preview. That's how the UI is designed, it's not an accidental loop.

@jsnajdr

jsnajdr commented Nov 5, 2026

Copy link
Copy Markdown
Member

Another possible improvement is splitting the block-list/index.tsx into two. It contains two separate things: Root + BlockList, and Items + BlockListItems. They are mostly independent from each other. Only the first one (Root) imports useInnerBlocksProps, and only the second one (BlockListItems) is imported by inner-blocks. Splitting them would completely break the block-list/index.tsx ↔ inner-blocks/index.tsx cycle.

Not sure if this alone fixes any errors, but is a good incremental and structural improvement of the dependency graph.

@jsnajdr

jsnajdr commented Nov 5, 2026

Copy link
Copy Markdown
Member

@retrofox I'm curious about one thing: if you discovered and are fixing these bugs, it means that some project uses the CJS exports from the @wordpress/* packages. Is that the Jest setup in Jetpack mentioned in Automattic/jetpack#54534, or is there anything else?

The most favored solution would be completely removing CJS from the packages, as mentioned in #86328 (comment). We are aware of the Jest consumers, but is there anything else?

There are many ESM-only NPM packages already, and any Jest setup must have some way to handle them. Could that solution be extended also to the @wordpress/* packages, so that the CJS usage is removed?

@simison

simison commented Nov 5, 2026

Copy link
Copy Markdown
Member

👋 also @anomiex or @tbradsha from Jetpack might be able to elaborate here regarding @jsnajdr 's question above.

@simison

simison commented Nov 5, 2026

Copy link
Copy Markdown
Member

@jsnajdr Digging into this more, looks like it was Jest (Automattic/jetpack#54512 (comment)), and there's a fix in Automattic/jetpack#54534

@anomiex

anomiex commented Nov 5, 2026

Copy link
Copy Markdown
Contributor

If you want to drop CommonJS entirely, fine. As you said, many other packages have done the same. But as long as you are supplying CommonJS, it should work properly.

Depending on what the package does (e.g. no top-level await), require(esm) might just work now if running jest with node 24.9+. Mocking might need updating though.

Another solution for jest is to run it with NODE_OPTIONS=--experimental-vm-modules and rewrite the tests in ESM. The tradeoff there being that the tests have to be rewritten, and sometimes that's less than straightforward.

Another is to tell it to transpile node_modules/whatever by overriding transformIgnorePatterns (which is what Automattic/jetpack#54534 does; I'd call that a workaround, not a fix). The tradeoff there being more CPU usage for transpiling more code.

@louwie17 louwie17 left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thanks for the updates! This works now: the memo warnings are gone, and InnerBlocks and BlockPreview both render from the CommonJS build. Nested blocks and the pattern previews also render fine in the browser on wp-env. It would be great to rebase this and get it merged. Approving for now, with one suggestion inline.


const BlockListItemsMemo = memo( BlockListItems );
// Wrapped because the circular import leaves `BlockListItems` undefined when the CommonJS build runs this line.
const BlockListItemsMemo = memo( function BlockListItemsMemoWrapper(

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think @jsnajdr's approach is the cleaner one: memoize BlockList and BlockListItems in block-list/index.tsx and import the memoized versions by name. That removes both wrappers and the extra export { BlockList }. I tried it locally and it works the same. Together with his split of block-list/index.tsx, it would remove the block-list ↔ inner-blocks cycle completely.

Happy for this to be a follow-up, but also happy if you'd like to make the change here right away.

This branch has not been deployed

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

Labels

[Package] Block editor /packages/block-editor [Type] Bug An existing feature does not function as intended

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants