usePersistentId

 
 
 
 

Overview

An editor hook that gives a block an identifier generated once and then kept, so that whatever points at it — a link, a hash — keeps working, and that hands a copy of the block a fresh one.


Signature

JavaScript
import usePersistentId from '../../hooks/usePersistentId';

usePersistentId({
    clientId,
    blockName: 'method/modal',
    attribute: 'modalId',
    value: modalId,
    generate: generateModalId,
    setAttributes,
    onCopy: (own, original) =>
        own.customId && own.customId === original.customId ? { customId: '' } : {},
});

Parameters

PropTypeDefaultDescription
clientIdstring(required)The block’s client id.
blockNamestring(required)The block type that shares the identifier space — copies are looked for among blocks of this name.
attributestring(required)The attribute that holds the identifier.
valuestring(required)The attribute’s current value.
generatefunction(required)Returns a new identifier.
setAttributesfunction(required)WordPress setAttributes.
onCopyfunction—Called when the block is found to be a copy, with the block’s attributes and the original’s; returns further attributes to reset alongside the identifier.

Behavior

  • Empty attribute: filled the first time the block is edited (the block has to be editable — a block whose editing mode is disabled is left alone).
  • Copies: a block that mounts carrying another mounted block’s identifier is a copy — a duplicate or a paste — and takes a fresh one, plus whatever onCopy returns. “Original” means the block that was already there, not the one that comes first in the document: a copy pasted above the original must not change the original, which links point at. Mounted blocks are tracked in a module-level set keyed by client id, so one set serves every editor and block preview.
  • Synced patterns and template parts: a block inside core/block or core/template-part is never regenerated. Every use of the pattern on the page is the same block with the same identifier, and writing to one writes to all of them.
  • Undo: the write is marked not persistent (__unstableMarkNextChangeAsNotPersistent), so undoing the insertion removes the block instead of clearing its identifier.

Usage by Blocks

BlockNotes
ModalmodalId from generateModalId() (lib/blocks/utils/modalId.js); onCopy clears a customId copied from the original.

Changelog

VersionDescription
2.0.0-beta26Introduced, with the Modal block (e12c9c0).