Skip to content

Commit 1ddadee

Browse files
authored
fix(createGlobalStyle): keep each global style's CSS when two differ only in their functions (#5847)
* fix(createGlobalStyle): keep each global style's CSS when ids collide 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. * test(createGlobalStyle): drop assertions on an id property 6.x never sets * fix(createGlobalStyle): key global style instances by sheet * fix(createGlobalStyle): bound server appends, keep definition order, reallocate on sheet swap * fix(createGlobalStyle): order same-id globals by mount, an update keeps its place * fix(createGlobalStyle): keep server-sheet entries so a repeat render keeps its siblings * docs: state the server-detection gate rule as the code has it
1 parent ed7b199 commit 1ddadee

7 files changed

Lines changed: 477 additions & 88 deletions

File tree

Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'styled-components': patch
3+
---
4+
5+
Each `createGlobalStyle` applies its own CSS when two global styles differ only in what their functions return, including bodies that are only a function (`createGlobalStyle\`${() => 'html { --a: 1; }'}\``). This is how a CSS reset and a color-mode style are often written together, for example xstyled's Preflight and ColorModeProvider. When both set the same property, the one mounted most recently wins, and a prop or theme update does not change which one that is.
6+
7+
When several mounts of one dynamic global style render on the server, the collected styles include every one of them, not only the last.

‎docs/build-architecture.md‎

Lines changed: 3 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -25,10 +25,9 @@ mode collect styles synchronously in a build where `__SERVER__` is false (#3551)
2525
the browser build work on a server: that build's tags are always DOM tags, so a server render there
2626
fails at the first `<style>` creation (see "Edge runtime").
2727

28-
Combine all three (`__SERVER__ || IS_RSC || ssc.styleSheet.server`) with one deliberate exception:
29-
`createGlobalStyle`'s server-cache cleanup drops the `IS_RSC` term, because the `IS_RSC` branch above
30-
it has already handled the render and returned, so reaching that line under RSC means there was
31-
nothing left to clean.
28+
Each gate uses the smallest subset of the three that covers its cases. `createGlobalStyle` renders
29+
during component execution on `IS_RSC || ssc.styleSheet.server`, without `__SERVER__`: the server
30+
build has no cleanup effect, so rendering there under jsdom would pile styles up across renders.
3231

3332
`IS_BROWSER` is `typeof window !== 'undefined' && typeof document !== 'undefined'`. Both halves are
3433
needed: a non-browser host can define `window` without a DOM. It is a runtime check, so bundlers

‎docs/global-styles.md‎

Lines changed: 48 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -1,29 +1,43 @@
11
# GlobalStyle Shared-Group Architecture
22

3-
Every component returned by a single `createGlobalStyle` call shares one stylesheet group, registered
4-
at call time via `StyleSheet.registerId(componentId)`. The returned component is wrapped in
5-
`React.memo`.
3+
Every mount with the same `componentId` shares one stylesheet group, registered at call time via
4+
`StyleSheet.registerId(componentId)`. The returned component is wrapped in `React.memo`.
65

7-
## Instance identity
8-
9-
Each mount needs its own instance ID, allocated by `allocateGSInstance`. The server allocates
10-
directly, since a server render is one-shot. The client allocates through a `useRef` so the ID stays
11-
stable across re-renders.
6+
The id hashes `JSON.stringify(rules)`, and functions serialize to `null`, so separate
7+
`createGlobalStyle` calls that differ only in their functions share an id and a group. Ids stay
8+
content-derived (stable across server and client); the shared registry below is what keeps each
9+
call's CSS.
1210

13-
`instanceRules`, a `Map<number, { name: string; rules: string[] }>` on the module-level `GlobalStyle`
14-
object, tracks each mount's compiled CSS. `computeRules()` flattens and compiles the CSS and caches it
15-
there under the name `componentId + instance`, making `instanceRules` the single source of truth for a
16-
rebuild.
11+
## Instance identity
1712

18-
`rebuildGroup()` clears the shared group and re-inserts from the surviving instances. It is O(N) in
19-
mounted instances, which is typically one to three.
13+
Each mount needs its own instance ID, allocated by `allocateGSInstance` from the sheet it renders
14+
into. The server allocates directly, since a server render is one-shot. The client keeps the ID in a
15+
`useRef` so it stays stable across re-renders, and allocates a fresh one from the new sheet when the
16+
`StyleSheetManager` sheet changes: independent sheets count from 1, so a kept ID would collide with
17+
one the new sheet hands out.
18+
19+
A module-level registry in `GlobalStyle.ts`,
20+
`WeakMap<StyleSheet, Map<componentId, Map<instance, { name, rules }>>>`, tracks each mount's
21+
compiled CSS, whichever `GlobalStyle` object produced it. It is keyed by sheet first because each
22+
sheet owns its own tag and instance counter; a per-request sheet's entries are collected with it.
23+
`computeRules()` flattens and compiles the CSS and stores it under the name `componentId + instance`,
24+
making the registry the single source of truth for a rebuild. An id's map is deleted with its last
25+
instance. Each render resolves the per-sheet, per-id map once and reuses it.
26+
27+
`rebuildGroup()` clears the shared group and re-inserts every surviving instance for the id on that
28+
sheet, in mount order (the map's insertion order), so the most recent mount wins a same-property
29+
conflict. A mount adds its entry at the end; an update replaces the entry in place, so a prop or
30+
theme change never moves a global. A global that unmounts and mounts again goes to the end. On first
31+
render this matches tree order, because globals render nothing and their effects fire in tree order.
32+
Globals with distinct ids are ordered by their groups, which are registered at definition. It is O(N)
33+
in mounted instances, which is typically one to three.
2034

2135
## Static and dynamic rules take different paths
2236

2337
`renderStyles` branches on `isStatic`, and the two branches share almost nothing.
2438

2539
Static rules never rebuild. The branch checks `hasNameForId(id, id + instance)` and inserts only on a
26-
miss. On a hit it still calls `computeRules` when `instanceRules` has no entry for the instance: that
40+
miss. On a hit it still calls `computeRules` when the registry has no entry for the instance: that
2741
is the rehydration case, where the CSS is already in the DOM from the server but the module-level
2842
cache is empty, and populating it is what lets `rebuildGroup` restore this instance if a sibling
2943
unmounts later.
@@ -35,8 +49,24 @@ length and element-wise equal, the CSSOM rebuild is skipped. That fast path is c
3549
caches, so a cache-based fast path would skip a rebuild the DOM still needs. Any new fast path here
3650
must make the same check.
3751

38-
Server-side `instanceRules` entries must be deleted explicitly once styles are collected, because no
39-
`useLayoutEffect` cleanup runs on the server.
52+
No `useLayoutEffect` cleanup runs on the server. A server sheet's entries stay until the sheet
53+
itself is collected (the registry is keyed by sheet, and a server sheet lives for one request), so a
54+
rebuild there sees every instance. RSC renders into the process-wide default sheet, so the RSC
55+
branch deletes each entry right after reading it.
56+
57+
An instance's first render into a server sheet appends: a rebuild would re-emit siblings' rules that
58+
a stream already flushed (`clearTag` empties the tag after each chunk but keeps the names). A repeat
59+
render of the same instance (a client re-render against a server sheet) rebuilds, so its earlier
60+
rules are replaced and its siblings' rules stay.
61+
62+
Only a sheet constructed with `isServer: true` (`ServerStyleSheet`, or a sheet derived from one)
63+
takes this path. The process-wide default sheet is never a server sheet, even on a server:
64+
`StyleSheet` reads `server` from its constructor argument, not from its defaults.
65+
66+
HMR swaps in a new `GlobalStyle` object under the same id. The cleanup-only effect depends on
67+
`globalStyle`, and React runs an updated layout effect's cleanup before any layout effect body, so
68+
the old object's `removeStyles` has already deleted the instance's entry and rebuilt the group when
69+
the render effect re-runs with the new object.
4070

4171
`rebuildGroup` must run synchronously. Nothing may yield between `clearRules` and the re-insert loop,
4272
or the group is observable while empty.
@@ -52,6 +82,6 @@ The client uses two separate `useLayoutEffect`s:
5282
2. A second holds the `removeStyles` cleanup, keyed on `[instance, sheet, globalStyle]`, so cleanup
5383
fires only on unmount, sheet swap or HMR.
5484

55-
Collapsing these into a single effect with per-render cleanup wipes `instanceRules` before the
85+
Collapsing these into a single effect with per-render cleanup wipes the instance's entry before the
5686
rules-equality fast path can hit, which costs a double `rebuildGroup` on every render of every
5787
dynamic global style (#5730).

‎packages/styled-components/src/constructors/createGlobalStyle.ts‎

Lines changed: 16 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,6 @@
11
import React from 'react';
22
import { IS_RSC, RSC_REDUNDANT_EMIT_WARN_THRESHOLD, STATIC_EXECUTION_CONTEXT } from '../constants';
3-
import GlobalStyle from '../models/GlobalStyle';
3+
import GlobalStyle, { deleteInstance, getInstance } from '../models/GlobalStyle';
44
import { useStyleSheetContext } from '../models/StyleSheetManager';
55
import { DefaultTheme, ThemeContext } from '../models/ThemeProvider';
66
import StyleSheet from '../sheet';
@@ -59,7 +59,7 @@ export default function createGlobalStyle<Props extends object>(
5959
const ssc = useStyleSheetContext();
6060
const theme = !IS_RSC ? React.useContext(ThemeContext) : undefined;
6161

62-
// Each mount needs a unique instance ID for the shared-group instanceRules cache.
62+
// Each mount needs a unique instance ID for the shared-group instance entries.
6363
// __SERVER__ is a build-time constant: the dead branch is entirely eliminated,
6464
// so React never sees a conditional hook call.
6565
// Server bundle: direct allocation (one-shot renders, no stability needed).
@@ -68,11 +68,15 @@ export default function createGlobalStyle<Props extends object>(
6868
if (__SERVER__) {
6969
instance = ssc.styleSheet.allocateGSInstance(styledComponentId);
7070
} else {
71-
const instanceRef = React.useRef<number | null>(null);
72-
if (instanceRef.current === null) {
73-
instanceRef.current = ssc.styleSheet.allocateGSInstance(styledComponentId);
71+
const instanceRef = React.useRef<{ instance: number; sheet: StyleSheet } | null>(null);
72+
// Independent sheets count from 1, so a number kept across a sheet swap could collide.
73+
if (instanceRef.current === null || instanceRef.current.sheet !== ssc.styleSheet) {
74+
instanceRef.current = {
75+
instance: ssc.styleSheet.allocateGSInstance(styledComponentId),
76+
sheet: ssc.styleSheet,
77+
};
7478
}
75-
instance = instanceRef.current;
79+
instance = instanceRef.current.instance;
7680
}
7781

7882
if (
@@ -128,17 +132,8 @@ export default function createGlobalStyle<Props extends object>(
128132
? [instance, ssc.styleSheet, globalStyle]
129133
: [instance, props, ssc.styleSheet, theme, ssc.stylis, globalStyle];
130134

131-
const prevGlobalStyleRef = React.useRef(globalStyle);
132-
133135
React.useLayoutEffect(() => {
134136
if (!ssc.styleSheet.server) {
135-
// HMR creates a new globalStyle instance but the componentId stays stable
136-
// (SWC plugin assigns by file location), so stale hasNameForId hits skip injection.
137-
if (prevGlobalStyleRef.current !== globalStyle) {
138-
ssc.styleSheet.clearRules(styledComponentId);
139-
prevGlobalStyleRef.current = globalStyle;
140-
}
141-
142137
renderStyles(instance, props, ssc.styleSheet, theme, ssc.stylis);
143138
}
144139
}, renderDeps);
@@ -165,12 +160,15 @@ export default function createGlobalStyle<Props extends object>(
165160
// the request; see "Per-instance emission" in docs/rsc-style-injection.md.
166161
if (IS_RSC) {
167162
const entry =
168-
typeof window === 'undefined' ? globalStyle.instanceRules.get(instance) : undefined;
163+
typeof window === 'undefined'
164+
? getInstance(ssc.styleSheet, styledComponentId, instance)
165+
: undefined;
169166
const css = entry ? joinRules(entry.rules) : '';
170167

171-
if (css) {
172-
globalStyle.instanceRules.delete(instance);
168+
// RSC renders into the process-wide default sheet, so the entry is freed here.
169+
deleteInstance(ssc.styleSheet, styledComponentId, instance);
173170

171+
if (css) {
174172
if (process.env.NODE_ENV !== 'production' && getGlobalEmitCounts) {
175173
const counts = getGlobalEmitCounts();
176174
const count = (counts.get(styledComponentId) || 0) + 1;
@@ -202,12 +200,6 @@ export default function createGlobalStyle<Props extends object>(
202200
}
203201
}
204202

205-
// Clean up server instance cache - no useLayoutEffect cleanup runs on the
206-
// server, so instanceRules would grow unboundedly across SSR requests.
207-
if (__SERVER__ || ssc.styleSheet.server) {
208-
globalStyle.instanceRules.delete(instance);
209-
}
210-
211203
return null;
212204
};
213205

‎packages/styled-components/src/constructors/test/createGlobalStyle.ssr.test.tsx‎

Lines changed: 41 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -3,7 +3,7 @@
33
*/
44
import React from 'react';
55
import ReactDOMServer from 'react-dom/server';
6-
import GlobalStyle from '../../models/GlobalStyle';
6+
import GlobalStyle, { liveInstanceCount } from '../../models/GlobalStyle';
77
import ServerStyleSheet from '../../models/ServerStyleSheet';
88
import { mainStylis } from '../../models/StyleSheetManager';
99
import StyleSheet from '../../sheet';
@@ -72,7 +72,7 @@ describe(`createGlobalStyle`, () => {
7272

7373
// First render with a fixed instance number (simulates WeakMap caching)
7474
gs.renderStyles(1, executionContext, sheet, mainStylis);
75-
expect(gs.instanceRules.size).toBe(1);
75+
expect(liveInstanceCount(sheet, gs.componentId)).toBe(1);
7676
expect(sheet.toString()).toMatchInlineSnapshot(`
7777
"body{color:red;}/*!sc*/
7878
data-styled.g3[id="sc-global-clearTag-test"]{content:"sc-global-clearTag-test1,"}/*!sc*/
@@ -83,7 +83,7 @@ describe(`createGlobalStyle`, () => {
8383
sheet.clearTag();
8484

8585
// Second render with SAME instance 1, SAME CSS - the exact regression path.
86-
// Bug: instanceRules still has instance 1's entry from render 1.
86+
// Bug: the registry still has instance 1's entry from render 1.
8787
// computeRules produces identical rules. rulesEqual returns true.
8888
// rebuildGroup is skipped. Tag is empty. CSS is lost.
8989
gs.renderStyles(1, executionContext, sheet, mainStylis);
@@ -93,6 +93,44 @@ describe(`createGlobalStyle`, () => {
9393
"
9494
`);
9595
});
96+
97+
it(`emits both stylesheets of two global styles that differ only in their functions`, () => {
98+
const sheet = new ServerStyleSheet();
99+
const First = createGlobalStyle`${() => 'html { --a: 1; }'}`;
100+
const Second = createGlobalStyle`${() => 'html { --b: 1; }'}`;
101+
102+
context.renderToString(
103+
sheet.collectStyles(
104+
<>
105+
<First />
106+
<Second />
107+
</>
108+
)
109+
);
110+
111+
// One group id carrying both instance names proves the two calls share an id.
112+
expect(stripWhitespace(stripComments(stripOuterHTML(sheet.getStyleTags())))).toBe(
113+
'html{ --a:1; } html{ --b:1; } data-styled.g4[id="sc-global-c"]{ content:"sc-global-c1,sc-global-c2,"} '
114+
);
115+
});
116+
117+
it(`collects the rules of two mounts of one dynamic global with different props`, () => {
118+
const sheet = new ServerStyleSheet();
119+
const Component = createGlobalStyle<{ color: string }>`body { color: ${p => p.color}; }`;
120+
121+
context.renderToString(
122+
sheet.collectStyles(
123+
<>
124+
<Component color="red" />
125+
<Component color="blue" />
126+
</>
127+
)
128+
);
129+
130+
expect(stripWhitespace(stripComments(stripOuterHTML(sheet.getStyleTags())))).toBe(
131+
'body{ color:red; } body{ color:blue; } data-styled.g5[id="sc-global-d"]{ content:"sc-global-d1,sc-global-d2,"} '
132+
);
133+
});
96134
});
97135

98136
function stripOuterHTML(html: string) {

0 commit comments

Comments
 (0)