Are Slice IDs Unique?


We've been using slice ids as keys in our Next.JS site for generated components. This has worked until we recently noticed duplication on some of the slice IDs.

Are these not guaranteed to be unique?

If it helps, sometimes, part of our editor's process is to duplicate an existing document and modify that new one. Could this cause duplicate slice IDs?

More reference: an example query [[any(document.type,["custom_type"])]] , yields some results, which we filter out only the slice ids present in the results of that query. (We use this JSONPath: $.results[*].data.body[*].id)

Here's a screenshot showing some duplicated slice IDs.

Thank you!

Further notes,

After digging, it does appear that you can cause duplicate slice ids, at least in Legacy Writing Room, by having a slice on a document, then duplicating that document.

While this isn't inherently a problem, we have a funny usecase where we link documents from another and pull in those slices to render them, using their data.

This caused a very weird duplicate key issue in our NextJS codebase. Not a problem, we append the slice index to the ID and it fixes the problem.

However, I wonder if this is a problem in slicemachine as well, because, indeed the slice ID is being treated as a unique key in the <SliceZone/> component. From the @prismicio/react source code.

Hi @michael.nguyen, that's an interesting situation!

TL;DR: We should probably use ${index}-${JSON.stringify(slice)} for all slice component keys due to the behavior your described.

Could you open a GitHub issue with the description you shared above so we can track the bug?

Open an issue on GitHub


Attaching the slice's index property to its id property may not be sufficiently unique. For example, if two slices with the same ID swap positions in the slice array, React may not re-render their components even if they should render differently.

JSON.stringify(slice) is the most reliable method to ensure two slices with the same ID, but different content, always renders correctly. JSON.stringify() is slow, but it probably isn't noticeable for objects as small as slices.

See this related GitHub thread: SliceZone component is rendering slices in the wrong order in Preview · Issue #101 · prismicio/prismic-react · GitHub

Will do! Thank you!

1 Like