June 8, 2026
Instance-proof components
The inline script trick from last time has a hidden assumption baked in. It hardcodes getElementById('feed'). That works right up until two of these components appear on the same screen, which on a social network happens constantly. A profile preview inside a feed, a quoted post inside another post, a comment thread inside a modal.
The collision
With a fixed id, the second instance overwrites the first. Both scripts target the same DOM node, so whichever runs last wins and the other instance silently breaks.
function FeedDensityProvider({ children }) {
return (
<>
<div id="feed">{children}</div>
<script
dangerouslySetInnerHTML={{
__html: `
const density = localStorage.getItem('feedDensity') || 'cozy'
document.getElementById('feed').dataset.density = density
`,
}}
/>
</>
)
}
The fix
React gives you useId for exactly this. It produces a stable, unique id per instance that matches between server and client, so each copy of the component talks only to its own node.
function FeedDensityProvider({ children }) {
const id = useId()
return (
<>
<div id={id}>{children}</div>
<script
dangerouslySetInnerHTML={{
__html: `
try {
const density = localStorage.getItem('feedDensity') || 'cozy'
document.getElementById('${id}').dataset.density = density
} catch (e) {}
`,
}}
/>
</>
)
}
Never hardcode an identifier in a component meant to be reused. The moment it ships, someone will render two of them next to each other.