Skip to content

infinite rerenders when using useInstanceId in template-part preview  #63713

@silaskoehler

Description

@silaskoehler

Description

I get infinite rerenders when i use useInstanceId() in my custom block and save it to an attribute if it changes.
for testing purpose i created a block using pnpx @wordpress/create-block@latest --variant dynamic and change the edit.js to this:

import { useBlockProps } from '@wordpress/block-editor';
import { useInstanceId } from '@wordpress/compose';

export default function Edit( { setAttributes, attributes } ) {
	const { uniqueId } = attributes;

	const instanceId = useInstanceId( Edit );

	useEffect( () => {
		console.log( uniqueId, instanceId );

		setAttributes( {
			uniqueId: instanceId,
		} );
	}, [ uniqueId ] );

	return <div { ...useBlockProps() }>uniqueId: { uniqueId }</div>;
}

In the template preview in the site editor (/wp-admin/site-editor.php?postType=wp_template) my block flickers and in the console I see infinite rerenders. The error only occurs when my block is in a Temaplte part.

Am I doing something wrong or is there a bug because it does a render every time I save the attribute. He doesn't do that in the block editor.

Step-by-step reproduction instructions

  1. Use default Theme and WP 6.6
  2. create a block using @wordpress/create-block@latest
  3. edit the edit.js as described above
  4. go to the template preview
  5. go to the console

Screenshots, screen recording, code snippet

Bildschirmaufnahme.2024-07-18.um.16.50.43.mov

Environment info

  • WordPress Studio
  • WordPress 6.6
  • PHP 8.1
  • Theme: Twenty Twenty-Four
  • no Plugins besides the custom block plugin

Please confirm that you have searched existing issues in the repo.

  • Yes

Please confirm that you have tested with all plugins deactivated except Gutenberg.

  • Yes

Metadata

Metadata

Assignees

No one assigned

    Labels

    Needs Technical FeedbackNeeds testing from a developer perspective.[Type] BugAn existing feature does not function as intended

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions