Repository navigation
fix(createGlobalStyle): keep each global style's CSS when two differ only in their functions - #5847
Conversation
🦋 Changeset detectedLatest commit: 48eff38 The changes in this PR will be included in the next version bump. This PR includes changesets to release 1 package
Not sure what this means? Click here to learn what changesets are. Click here if you're a maintainer who wants to add another changeset to this PR |
There was a problem hiding this comment.
ℹ️ No blocking issues — the backport is faithful and well covered; one follow-up question on the id counter's process-global scope.
Reviewed changes
Backport of #5846 to the 6.x line, fixing #5845 (function-bodied global styles collapse onto one id, so only the last one renders).
- New id helper —
packages/styled-components/src/utils/globalStyleId.ts: static rules still hash their JSON (unchanged from base, so existing static ids/SSR markers are byte-stable); rules containing a function mix a per-serialization count into the hash, starting at the first call, so colliding function-bodied globals get distinct ids.containsFunctionwalks the rules, treating styled components and keyframes as function-free since they carry their own id in the JSON. - Wiring —
createGlobalStyle.tscalls the helper instead ofgenerateComponentId(JSON.stringify(rules)). - Tests — new unit suite for the helper, a shared
globalStyleShapesmatrix exercised on the client and throughServerStyleSheetSSR, updated RSC snapshot ids, and the function-body count reset between cases insetupTestFramework.ts.
I read the full diff, confirmed the core helper is identical to the already-reviewed main version, ran the full web suite (1035 passed / 61 suites), tsc --noEmit, and prettier (all clean). I also reverted only the createGlobalStyle.ts id line to the base expression and re-ran the new tests: they fail (19 client + SSR cases), so the new coverage is load-bearing rather than passing against the old code.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
|
Follow-up detail for the note in my review (
The consequence for hydration: on a warm server that has already evaluated other routes' modules, a page's function-bodied ids are offset by whatever earlier routes issued, while a fresh client starts its count at 0. When they differ, rehydration registers the server's group names and the client inserts its own group, duplicating the CSS rather than matching it — which is the case the changeset's "hydrates when the calls run in the same order" sentence rules out. Is the supported deployment one where the module graph is re-evaluated per render (serverless / fresh process), so the count always starts at 0? If not, the changeset's third paragraph should be qualified to cover the process-wide count, or the counter needs a per-request reset. I did not stand up a real multi-route server to confirm this empirically, so treat it as a question rather than a confirmed bug. Technical details# Function-body ids depend on the process-wide issuance count
## Mechanism
- `packages/styled-components/src/utils/globalStyleId.ts:12` — `issuedBySerialization` is module-global and cleared only by `resetGlobalStyleComponentIds()`, which production code never calls.
- Whole-function bodies serialize to `"[null]"`, so every such call shares one counter; mixed shapes share a counter keyed on their static skeleton.
- Ids are `hash(serialized + "\0" + issued)`, so `issued` is a process-wide ordinal, not a per-render one.
## Consequence
- Warm server (modules cached): a route's function-bodied globals are issued after whatever other routes already issued, so their counts carry an offset.
- Fresh client: the count starts at 0 for whatever the page bundle evaluates.
- On mismatch, `rehydrateSheet` registers the server's ids while the client registers its own, so the CSS is duplicated.
## Required outcome
- Either confirm the deploy target re-evaluates modules per render (so counts start at 0 and the guarantee holds), or qualify the changeset's hydration claim to cover the process-wide count. A per-request reset would need a request boundary the helper currently has none of.
|
Instance entries move to a module-level registry keyed by component id, so a rebuild re-inserts every global style sharing the id; server renders append a first-seen instance.
3167391 to
8d7d520
Compare
There was a problem hiding this comment.
ℹ️ No blocking issues — the fix was reworked into a shared per-id registry since the last review; one dead test assertion inline.
Reviewed changes
The branch was rewritten since the prior review: it drops the previous id-salting helper entirely and instead keeps the content-derived ids and fixes the shared-group rebuild.
- Moved the per-instance rule cache into a shared per-id registry —
GlobalStyle.tsreplaces the object's privateinstanceRuleswith a module-levelMap<componentId, Map<instance, {name, rules}>>, so instances created by differentcreateGlobalStylecalls that share an id are tracked together. rebuildGroupnow restores every surviving instance for the id — it clears the group and re-inserts from the shared registry rather than only the current object's instances, which is what stops one colliding call from wiping the other's CSS.- Server path appends first-seen instances —
renderStylesinserts instead of rebuilding whenstyleSheet.server && !prev, since server entries are deleted right after each instance renders and a rebuild would drop earlier instances. - HMR swap calls
removeStyles— drops the instance's own entry before re-rendering so the rules-equality fast path cannot skip the re-insert. - Tests and docs — removed the 18-shape matrix and the id-helper unit suite, added a focused
createGlobalStyle with the same idsuite plus one SSR case, and updateddocs/global-styles.mdand the changeset. Full web suite runs green here (991 passed / 60 suites).
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found — the sole prior finding was resolved and the PR is mergeable as-is.
Reviewed changes
The only commit since the prior review is a test-only cleanup that addresses prior feedback.
- Dropped the vacuous
styledComponentIdassertion — removed the client "gives function-only bodies one id" case and replaced the SSR counterpart's assertion with a comment explaining that the shared group id in the snapshot already proves the two calls share an id. Shared-id coverage remains pinned by the SSR snapshot (data-styled.g4[id="sc-global-c"]{ content:"sc-global-c1,sc-global-c2,"}) plus the client behavioral cases.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The only commit since the prior pullfrog review keys the shared per-instance registry by stylesheet, so entries from different sheets can no longer collide or be re-inserted into each other.
- Registry keyed by
StyleSheet—GlobalStyle.tschanges the module-level registry fromMap<componentId, Map<instance, ...>>toWeakMap<StyleSheet, Map<componentId, Map<instance, ...>>>. Each sheet owns its own tag, so scoping by sheet keeps same-id/same-instance entries from one sheet out of another's rebuild. - All call sites thread the sheet through —
getInstance,deleteInstance, andliveInstanceCountnow take the stylesheet, and every caller inGlobalStyle.ts/createGlobalStyle.tspasses the samestyleSheetit wrotecomputeRulesagainst, so reads, deletes, andrebuildGroupall target one sheet. - New two-sheet test — a
createGlobalStyle with the same idcase renders two same-id globals into two independent sheets and asserts each tag holds only its own group, including after either unmounts. - Docs updated —
docs/global-styles.mddescribes the sheet-first registry and why it is keyed that way.
I traced every getInstance/deleteInstance/rebuildGroup call site for sheet consistency, verified the RSC and ServerStyleSheet paths always resolve a stable sheet within a render, and ran the web suite green (991 passed / 60 suites) plus the focused createGlobalStyle files (67 passed). This sheet-scoping also removes the earlier cross-request clobber exposure the previous commit carried over from base.
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…reallocate on sheet swap
There was a problem hiding this comment.
Important
One edge case in the new server-append logic can drop a sibling mount's collected CSS. Details inline.
Reviewed changes
Two commits landed since the prior pullfrog review (838e9876), both reworking the shared-group instance registry.
- Bounded server appends — a repeat render of the same instance into a per-request collection now rebuilds (replacing its earlier rules) instead of appending duplicates, keyed off
styleSheet.hasNameForId(id, next.name). - Reallocate the instance id on a sheet swap — the client
useRefnow stores{ instance, sheet }and allocates a fresh id from the new sheet whenStyleSheetManagerswaps sheets, since independent sheets count instances from 1. - Mount-order conflict resolution — dropped the
orderfield and stable sort;rebuildGroupre-inserts in the registry map's insertion order, so the most recently mounted global wins a same-property conflict and a prop/theme update keeps its place. - HMR relies on effect teardown ordering — removed the render-effect
prevGlobalStyleRef/removeStylesspecial case; the cleanup-only effect's teardown now runs before the render effect re-runs with the newglobalStyle. - Registry refactor —
computeRulessplit intobuildEntry+entriesFor;renderStylesresolves the per-sheet/per-id map once and reuses it. - Tests, docs, changeset — added a repeated-render server case, a two-mount SSR case, mount-order and in-place-update cases, and a sheet-swap case; updated
docs/global-styles.mdand the changeset.
I read the full delta, traced the server append / rebuild branches against Sheet.clearRules (which clears names too), and reproduced the finding below with a focused unit case. The full createGlobalStyle suite is green here (72 passed).
deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
…keeps its siblings
There was a problem hiding this comment.
ℹ️ No critical issues — the prior finding is fixed and well covered; one stale doc reference to tidy up.
Reviewed changes
The only commit since Pullfrog's prior review (f840c57b) keeps a server sheet's instance entries for the sheet's lifetime, so a repeat render rebuilds with every sibling instead of dropping the ones already emitted and deleted.
- Server entries persist for the sheet — the per-render
deleteInstancein the non-RSC server path is removed; a server sheet's registry entries now live until the sheet is collected. The RSC branch still deletes its own entry right after reading it, now unconditionally rather than only when the CSS is non-empty. - Append guard simplified — the dynamic branch appends only when
styleSheet.server && !prev, dropping thehasNameForIdcheck that pushed a repeat render into a rebuild whose registry had already been emptied. - Tests — the repeated-render unit case now renders instances 1, 2, 1 (no per-render delete) and expects both siblings in the group; a new server-sheet case rerenders one sibling and asserts the other survives.
- Docs —
docs/global-styles.mdrewritten for sheet-lifetime server entries and the append/rebuild split.
I traced the append and rebuild branches across GlobalStyle.ts, createGlobalStyle.ts, Sheet.ts, and ServerStyleSheet, confirmed a name registered without a registry entry is unreachable on a server === true sheet (so the simplified guard cannot double-append), and ran the focused createGlobalStyle suites green (59 passed / 2 suites).
ℹ️ docs/build-architecture.md still documents the removed cleanup as the server-detection exception
The commit removes createGlobalStyle's server-cache cleanup, but docs/build-architecture.md still presents that exact cleanup as "the one deliberate exception" to the __SERVER__ || IS_RSC || ssc.styleSheet.server rule, with a rationale about the IS_RSC branch above it. The paragraph now describes deleted code, and the gate that actually remains in createGlobalStyle is not the exception it names.
Technical details
# Stale server-detection exception in build-architecture.md
## Affected sites
- `docs/build-architecture.md:28-31` — "Combine all three ... with one deliberate exception: `createGlobalStyle`'s server-cache cleanup drops the `IS_RSC` term, because the `IS_RSC` branch above it has already handled the render and returned ...". That cleanup is the `if (__SERVER__ || ssc.styleSheet.server) { deleteInstance(...) }` block removed in `48eff387`.
- `packages/styled-components/src/constructors/createGlobalStyle.ts:110` — the only remaining combined gate is `if (IS_RSC || ssc.styleSheet.server)`, which drops `__SERVER__` for its own reason (inline comment at lines 101-109). It is not the `IS_RSC`-dropping cleanup the doc describes.
## Required outcome
- `docs/build-architecture.md` no longer documents a cleanup that does not exist. Either drop the exception sentence, or restate the exception the code currently makes.
## Suggested approach (optional)
- The removed block was the sole home for this "one deliberate exception" claim; after deletion, the union rule stands with no exception in `createGlobalStyle`, so deleting the paragraph is the smallest correct edit. If the `IS_RSC || ssc.styleSheet.server` render gate is meant to be the documented exception, its rationale differs from the text currently in the file.deepseek-v4.1-flash (free via Pullfrog for OSS) | 𝕏
There was a problem hiding this comment.
✅ No new issues found.
Reviewed changes
The only commit since Pullfrog's prior review (48eff387) corrects the build-architecture paragraph that review flagged as stale.
- Restated the server-detection gate rule —
docs/build-architecture.mdno longer describes the removedcreateGlobalStyleserver-cache cleanup as "the one deliberate exception" to the three-flag union. It now states that each gate uses the smallest subset of__SERVER__,IS_RSCandstyleSheet.serverthat covers its cases, and explains whycreateGlobalStylerenders onIS_RSC || ssc.styleSheet.serverwithout__SERVER__: the server build has no cleanup effect, so rendering there under jsdom would accumulate styles across renders.
I checked the new paragraph against createGlobalStyle.ts:110 and the rationale at :101-109; the gate and the reason match the code. Docs-only, no behavioral change.
deepseek-v4.1-flash-1017 (free via Pullfrog for OSS) | 𝕏

Two
createGlobalStylecalls whose templates differ only in their interpolated functions, such as xstyled's Preflight and ColorModeProvider, could wipe each other's CSS. Mounting, rerendering, or unmounting one of them removed the other's rules from the page.What changes
createGlobalStyle`${() => 'html { --a: 1; }'}`).Class names and global style ids are unchanged, so server-rendered pages hydrate as before.