Skip to content

Commit 1c0e309

Browse files
authored
fix: emit RSC styles per instance so they survive Suspense reveals (#5808)
RSC style emission deduped inline <style> tags across a request via a React.cache-scoped Set. That ledger outlives a Suspense fallback's DOM: a component rendered in a fallback recorded its class, the resolved child then emitted nothing, and React discarded the fallback (CSS and all) on reveal, leaving the resolved element with a class but no rule. Each server-rendered instance now emits exactly its own render's classes (leaf plus the :where()-wrapped base chain), read per name from the compiled cache so emission stays O(chain) even for a dynamic base. Referenced keyframes are scoped per render rather than flushing every keyframe in the request. Styles stay inline (no precedence hoisting) so cross-boundary extensions keep winning by source order (#5672) and stylisPluginRSC's child-index rewriting holds. A development-only warning fires when one component emits a very large number of tags in a single render, pointing at the attrs + inline CSS-variable pattern. createGlobalStyle carries the same request-scoped dedup and is intentionally left for a separate change, since its dedup is documented behavior.
1 parent 52c5f6e commit 1c0e309

9 files changed

Lines changed: 323 additions & 142 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+
Fixed styles disappearing from a server-rendered component when it is revealed from behind a React `<Suspense>` boundary, such as a streaming Next.js route (including `cacheComponents`). A component shown first in a Suspense fallback and then in the resolved content kept its class name but lost its CSS, because the rule had been emitted only inside the fallback that React discards on reveal.
6+
7+
Each server-rendered instance now carries its own inline `<style>`, so its styles always travel with it and survive the boundary. Identical rules compress away under gzip, so the extra output is negligible; only a very large repeated list (thousands of instances of one component on a single page) is worth collapsing into a shared class, and a development-only warning points that out if it happens.

‎AGENTS.md‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -73,7 +73,7 @@ mapped below.
7373
- `pnpm --filter styled-components bench` -- Run all benchmarks (web + native + RSC)
7474
- `pnpm --filter styled-components bench:web` -- Run web benchmarks
7575
- `pnpm --filter styled-components bench:native` -- Run native benchmarks (parser + render)
76-
- `pnpm --filter styled-components bench:rsc` -- Run RSC benchmarks (renderToString + dedup + React baseline)
76+
- `pnpm --filter styled-components bench:rsc` -- Run RSC benchmarks (renderToString + per-instance emission + React baseline)
7777
- `pnpm test:prerelease-notes` -- Regenerate prerelease GitHub release-note markdown locally (set `GITHUB_REPOSITORY=owner/name`; optional `CHANGESET_NOTES_ROOT`, `RELEASE_NOTES_OUTDIR`)
7878

7979
## Specifications
@@ -89,7 +89,7 @@ it rather than restating it.
8989
- [docs/global-styles.md](docs/global-styles.md) -- `createGlobalStyle`'s shared-group architecture,
9090
instance lifecycle, rebuild fast path
9191
- [docs/rsc-style-injection.md](docs/rsc-style-injection.md) -- how styles reach the page from server
92-
components, dedup, `:where()` wrapping, `stylisPluginRSC`
92+
components, per-instance emission, `:where()` wrapping, `stylisPluginRSC`
9393
- [docs/create-theme.md](docs/create-theme.md) -- the `createTheme` CSS-variable contract
9494
- [docs/attrs.md](docs/attrs.md) -- `attrs` precedence and its escape hatches
9595
- [docs/type-contracts.md](docs/type-contracts.md) -- how the compile-only type suites are written and

‎docs/rsc-style-injection.md‎

Lines changed: 35 additions & 16 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,11 @@ Server component output is not hydrated by React, so an inline tag causes no hyd
1010
which never runs over RSC output.
1111

1212
Inline body styles land after the registry's `<head>` styles in source order, so a cross-boundary
13-
extension (an RSC component extending a client component) wins the cascade.
13+
extension (an RSC component extending a client component) wins the cascade. This source-order
14+
placement is load-bearing and is why styles are not hoisted to `<head>` via `precedence`: the server
15+
never sees a client component's base class, so it cannot make the extension win by specificity, and
16+
`precedence` buckets order the RSC render ahead of the client registry, which would flip the cascade
17+
(#5672). The child-index selector plugin below likewise depends on the tag staying an inline sibling.
1418

1519
No cleanup of RSC style tags is needed: they are the sole source of CSS for server-only components.
1620

@@ -20,20 +24,35 @@ Base-level CSS in an inheritance chain is wrapped in `:where()` for zero specifi
2024
duplicate base CSS from sibling extensions sharing a base would override an earlier extension's
2125
styles.
2226

23-
## Deduplication
24-
25-
Inline `<style>` tags are deduplicated per render through name-based tracking in a `React.cache`-scoped
26-
Set. A dedup hit skips CSS collection entirely: no `getGroup`, no `:where()` wrapping. A dynamic
27-
component with several variants therefore emits CSS only for new names rather than for the full
28-
accumulated group. Compiled CSS is cached on `ComponentStyle` and `Keyframes` through a `WeakMap`,
29-
which persists across `React.cache` resets and is dead-code eliminated in the browser build.
30-
31-
Keyframe rules are deduplicated separately, by keyframe ID rather than by class name, against the same
32-
per-render Set. On this branch they are concatenated ahead of the component CSS and emitted in the
33-
*same* `<style>` tag: a styled component renders at most one style element, as
34-
`Fragment(styleElement, element)`. Dedup survives the concatenation because each keyframe ID is
35-
recorded as it is emitted, so a keyframe already written this render contributes nothing to the next
36-
component's string.
27+
## Per-instance emission
28+
29+
Each server-rendered instance emits its own inline `<style>` holding exactly that render's classes:
30+
the leaf class from `generateAndInjectStyles` plus each `:where()`-wrapped base level. Rules are read
31+
per name from the compiled cache (`getCompiledCSSForName`), so emission is O(chain length) per
32+
instance rather than re-scanning a component's whole accumulated variant group. Compiled CSS is cached
33+
on `ComponentStyle` and `Keyframes` through a `WeakMap`, which is dead-code eliminated in the browser
34+
build. Every name reaching emission was compiled by `generateAndInjectStyles` before it registered its
35+
class, so the per-name lookup always hits; there is no tag-group fallback.
36+
37+
There is deliberately no cross-instance or cross-request deduplication. A request-scoped `React.cache`
38+
Set was tried and removed: `React.cache` is request-wide with no per-Suspense-boundary scope, so a
39+
rule emitted only inside a Suspense fallback was recorded once, skipped for the resolved child, then
40+
removed with the fallback when React revealed the boundary, leaving the resolved element with a class
41+
but no rule (#5808). The alternatives were ruled out by their costs, not overlooked: hoisting via
42+
`precedence` would dedup and survive the reveal but breaks #5672 and the child-index plugin (see
43+
above); no per-boundary cache scope exists to make a ledger safe. Byte-identical duplicates are the
44+
only output dedup ever collapsed, and they cost about a byte each after gzip (measured: 1000 identical
45+
tags compress to ~0.5% of their raw size), so per-instance emission is the minimal correct behavior.
46+
47+
Keyframes are emitted per instance too, scoped to the render by matching each keyframe group's
48+
resolved name against the render's CSS. A referenced keyframe's rules are concatenated ahead of the
49+
component CSS in the _same_ `<style>` tag: a styled component renders at most one style element, as
50+
`Fragment(styleElement, element)`.
51+
52+
A development-only warning fires once a single component emits `RSC_REDUNDANT_EMIT_WARN_THRESHOLD`
53+
(1000) tags in one render, the point at which a very large repeated list should share one className
54+
instead. The counter is `React.cache`-scoped and gated on `NODE_ENV`, so production drops both the
55+
warning and its bookkeeping.
3756

3857
## Per-render reset
3958

@@ -73,7 +92,7 @@ Object.defineProperty` to keep a stable `.name` after minification. It does two
7392
**Child-index pseudo-selectors.** `:first-child`, `:last-child`, `:only-child`, `:nth-child()` and
7493
`:nth-last-child()` are rewritten with CSS Selectors Level 4 `of S` syntax to exclude
7594
`style[data-styled]` from the count. `:only-child` becomes the conjunction of a first and a last test.
76-
An `:nth-child()`/`:nth-last-child()` that already carries its own ` of ` clause is left alone rather
95+
An `:nth-child()`/`:nth-last-child()` that already carries its own `of` clause is left alone rather
7796
than double-wrapped. This is a precise, spec-level fix, and it requires browser support for `of S`
7897
(Chrome 111+, Firefox 113+, Safari 9+).
7998

‎packages/sandbox/app/components/sidebar.tsx‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,7 @@ const sections = [
1111
title: 'Tests',
1212
items: [
1313
{ href: '/rsc', label: 'RSC' },
14+
{ href: '/suspense-5808', label: 'Suspense (#5808)' },
1415
{ href: '/client-example', label: 'Client Components' },
1516
{ href: '/global-style-test', label: 'Global Styles' },
1617
],
Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
import { Suspense } from 'react';
2+
import styled from 'styled-components';
3+
import { SectionDesc } from '../components/test-ui';
4+
import theme from '../lib/theme';
5+
6+
/**
7+
* Repro for #5808: an inline <style> tag emitted while rendering a Suspense
8+
* fallback is deduped away when the resolved content renders the same styled
9+
* component, then React discards the fallback subtree (and its <style>),
10+
* leaving the resolved element with a class but no matching rule.
11+
*
12+
* SharedPanel appears ONLY inside the Suspense subtree, in both the fallback
13+
* and the resolved child, so the fallback is the first (and only) emitter of
14+
* its rule. AlwaysPanel lives in the static shell as a control: its styling
15+
* must survive, proving the pipeline itself works.
16+
*/
17+
18+
async function SlowContent() {
19+
await new Promise(resolve => setTimeout(resolve, 1500));
20+
return (
21+
<SharedPanel data-testid="resolved-panel">
22+
Resolved content. This panel must stay crimson after the fallback swaps
23+
out. If it renders unstyled (white), #5808 has regressed: its rule reached
24+
the DOM only inside the discarded fallback.
25+
</SharedPanel>
26+
);
27+
}
28+
29+
export default function Suspense5808Page() {
30+
return (
31+
<Wrapper>
32+
<Heading>#5808 Suspense inline &lt;style&gt; removal</Heading>
33+
34+
<SectionDesc>
35+
The blue control panel lives in the static shell and proves the pipeline works. The panel
36+
below streams in behind Suspense and is the actual test: it must be crimson once it replaces
37+
the fallback. A white (unstyled) panel means #5808 has regressed.
38+
</SectionDesc>
39+
40+
<AlwaysPanel data-testid="control-panel">
41+
Control panel (static shell). Always blue.
42+
</AlwaysPanel>
43+
44+
<Suspense
45+
fallback={
46+
<SharedPanel data-testid="fallback-panel">Loading… (fallback, crimson)</SharedPanel>
47+
}
48+
>
49+
<SlowContent />
50+
</Suspense>
51+
</Wrapper>
52+
);
53+
}
54+
55+
const Wrapper = styled.div`
56+
max-width: 720px;
57+
margin: 0 auto;
58+
padding: 40px 24px;
59+
display: flex;
60+
flex-direction: column;
61+
gap: 16px;
62+
`;
63+
64+
const Heading = styled.h1`
65+
font-size: 24px;
66+
color: ${theme.colors.text};
67+
`;
68+
69+
/** Rendered in the static shell; emits its own rule that is never discarded. */
70+
const AlwaysPanel = styled.div`
71+
padding: 24px;
72+
border-radius: 8px;
73+
color: white;
74+
font-size: 16px;
75+
background-color: rgb(37, 99, 235);
76+
`;
77+
78+
/** Rendered ONLY inside the Suspense subtree (fallback + resolved child). */
79+
const SharedPanel = styled.div`
80+
padding: 24px;
81+
border-radius: 8px;
82+
color: white;
83+
font-size: 16px;
84+
background-color: rgb(220, 20, 60);
85+
`;

‎packages/styled-components/src/bench/rsc.test.tsx‎

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,8 +4,8 @@
44
* Run: pnpm --filter styled-components bench:rsc
55
*
66
* Measures server-side renderToString performance with IS_RSC=true,
7-
* including inline style tag emission, dedup, :where() wrapping,
8-
* and keyframe handling.
7+
* including inline style tag emission, per-instance emission of repeated
8+
* components, :where() wrapping, and keyframe handling.
99
*/
1010

1111
// Mock React.cache - scoped per render via manual clear
@@ -163,8 +163,8 @@ describe('RSC benchmarks', () => {
163163
});
164164
});
165165

166-
it('dedup efficiency', () => {
167-
console.log('\n--- Dedup (1K iterations, median of 5) ---');
166+
it('repeated-component emission efficiency', () => {
167+
console.log('\n--- Repeated-component emission (1K iterations, median of 5) ---');
168168

169169
const Item = styled.div`
170170
color: red;

0 commit comments

Comments
 (0)