In the current project I’m working on, we export all the icons as SVGs from Figma, then convert them into React components using SVGR, and finally setting all the color values to currentColor
so we can control it by simply setting the color of the parent <svg>
element.
When the SVG contains something like a <linearGradient>
element, Figma generates one random ID for it so that other elements can reference it. This causes a problem when rendering the same icon in two different colors, because browsers only register the first occurrence of an ID and ignore all other duplicates. That means even though the two SVG elements have different colors, the second element always has the same <linearGradient>
as the first one. To solve this we need to find a way to give every <linearGradient>
element a unique ID.
useId()
React first introduced this hook for generating unique IDs, which by definition is the perfect solution to the above problem. We can see in the code changes in this PR that for client side rendering, the IDs are generated by a global counter called globalClientIdCounter
, which just increment one for every new ID.
But this method creates unstable IDs, which means that every re-render creates a different ID for the same component. And for server side rendering, this can cause a mismatch and lead to hydration failure. So for server side components, the useId
hook uses a different approach that generates IDs based on the position of current component inside the whole render tree and its placement among its sibling elements.