How do I generate a stable unique ID in React with SSR?

I'm using SSR in Next.js. I'm trying to generate a unique ID in a component to use in a DOM element's id attribute. This component may be used multiple times on a page so each component instance needs its id to be unique. However, doing something like the following on each render of the component results in a server/client mismatch (component creates new ID on each render, so server and client do not match):

const gradientId = `linear-gradient-${uuid().slice(0, 8)}`

Stuff I've tried:

  • generating the ID as a default useState value
  • generating the ID right outside the component (same file, just above component definition)
  • generating the ID inside a useMemo

All seem to suffer from the client/server mismatch issue. Is there a good way to do this? Is there something stable in the component instance I can base the ID on instead (maybe React generates one I can use?).

I should also note I’m stuck on React 17 so I don’t have access to React 18’s useId, which seems aimed at solving this exact problem!

Any ideas appreciated - thanks!



Comments

Popular posts from this blog

Spring Elasticsearch Operations

Network Error and Timeout on Authorize.net JS

Object oriented programming concepts (OOPs)