Skip to content

Version Packages - #5687

Merged
quantizor merged 1 commit into
mainfrom
changeset-release/main
Apr 9, 2026
Merged

quantizor merged 1 commit into
mainfrom
changeset-release/main

Conversation

@quantizor

@quantizor quantizor commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor

This PR was opened by the Changesets release GitHub action. When you're ready to do a release, you can merge this and the packages will be published to npm automatically. If you're not ready to do a release yet, that's fine, whenever you add more changesets to main, this PR will be updated.

Releases

[email protected]

Minor Changes

  • b0f3d29: .attrs() improvements: props supplied via attrs are now automatically made optional on the resulting component (previously required even when attrs provided a default). Also fixes a bug where the attrs callback received a mutable props object that could be changed by subsequent attrs processing; it now receives an immutable snapshot.

  • 2a973d8: Dropped IE11 support: ES2015 build target, inlined unitless CSS properties (removing @emotion/unitless dependency), removed legacy React class statics from hoist and other unnecessary code.

  • 9e07d95: Add createTheme(defaultTheme, options?) for CSS variable theming that works across RSC and client components.

    Returns an object with the same shape where every leaf is var(--prefix-path, fallback). Pass it to ThemeProvider for stable class name hashes across themes (no hydration mismatch on light/dark switch).

    const theme = createTheme({ colors: { primary: '#0070f3' } });
    // theme.colors.primary → "var(--sc-colors-primary, #0070f3)"
    // theme.raw → original object
    // theme.vars.colors.primary → "--sc-colors-primary"
    // theme.resolve(el?) → computed values from DOM (client-only)
    // theme.GlobalStyle → component that emits CSS var declarations

    vars exposes bare CSS custom property names (same shape as the theme) for use in createGlobalStyle dark mode overrides without hand-writing variable names:

    const { vars } = createTheme({ colors: { bg: '#fff', text: '#000' } });
    
    const DarkOverrides = createGlobalStyle`
      @media (prefers-color-scheme: dark) {
        :root {
          ${vars.colors.bg}: #111;
          ${vars.colors.text}: #eee;
        }
      }
    `;

    Options: prefix (default "sc"), selector (default ":root", use ":host" for Shadow DOM).

  • 79cc7b4: Add first-class CSP nonce support. Nonces can now be configured via StyleSheetManager's nonce prop (recommended for Next.js, Remix), ServerStyleSheet's constructor, <meta property="csp-nonce"> (Vite convention), <meta name="sc-nonce">, or the legacy __webpack_nonce__ global.

  • b0f3d29: Rearchitect createGlobalStyle to use shared stylesheet groups.

    All instances of a createGlobalStyle component now share a single stylesheet group, registered once at definition time. This fixes unmounting one instance removing styles needed by others (createGlobalStyle stylesheet removed when a second instance unmounts, breaking styles on still-mounted instances #5695), styles scattering after remount (CreateGlobalStyles Rendered After Component Styles #3146), and group ID leaks during SSR (createGlobalStyle creates memory leak in Next.js #3022).

    CSS injection order is now fully determined at definition time (lower group ID = earlier in stylesheet). Render order no longer affects CSS order. Keyframes defined before a component correctly appear before that component's rules.

    Also fixes: O(n^2) performance regression in jsdom test environments from unbounded rule accumulation, and stale static global styles during client-side HMR (effect deps now include the globalStyle reference so module re-evaluation triggers re-injection).

  • b0f3d29: Significant render performance improvements via three-layer memoization and hot-path micro-optimizations. Client-only; server renders are unaffected.

    Re-renders that don't change styling now skip style resolution entirely. Components sharing the same CSS (e.g., list items) benefit from cross-sibling caching. Hot-path changes include forEach → for/for...of, template literal → manual concat, and reduced allocations.

    Benchmarks vs 6.3.12:

    • Parent re-render (most common): 3.3x faster
    • First mount: 1.7-2.5x faster
    • Prop cycling: 2.3-2.4x faster
    • 10K heavy layouts: 1.9x faster
    • No regressions on any benchmark
  • 9ada92b: React Server Components support: inline style injection, deduplication, and a new stylisPluginRSC for child-index selector fixes.

    Inline style injection: RSC-rendered styled components emit <style data-styled> tags alongside their elements. CSS is deduplicated per render via React.cache (React 19+). Extended components use :where() zero-specificity wrapping on base CSS so extensions always win the cascade regardless of injection order.

    StyleSheetManager works in RSC: stylisPlugins and shouldForwardProp are now applied in server component environments where React context is unavailable.

    stylisPluginRSC — opt-in stylis plugin that fixes :first-child, :last-child, :nth-child(), and :nth-last-child() selectors broken by inline <style> tags shifting child indices. Rewrites them using CSS Selectors Level 4 of S syntax to exclude styled-components style tags from the count.

    import { StyleSheetManager, stylisPluginRSC } from 'styled-components';
    
    <StyleSheetManager stylisPlugins={[stylisPluginRSC]}>{children}</StyleSheetManager>;

    The plugin rewrites :first-child, :last-child, :nth-child(), and :nth-last-child() using CSS Selectors Level 4 of S syntax to exclude injected style tags from the child count.

    Browser support: Chrome 111+, Firefox 113+, Safari 9+ (~93% global). In unsupported browsers, the entire CSS rule is dropped — only opt in if your audience supports it. Use :first-of-type / :nth-of-type() as a universally compatible alternative.

    HMR: Stale styles during client-side HMR are detected and invalidated when module re-evaluation creates new component instances while IDs remain stable (SWC plugin assigns IDs by file location). createGlobalStyle additionally clears stale sheet entries when the instance changes between renders.

    The plugin is fully tree-shakeable — zero bytes in bundles that don't import it.

Patch Changes

  • b0f3d29: Expose as and forwardedAs props in React.ComponentProps extraction for styled components
  • 553cbb4: Fix memory leak in long-running apps using components with free-form string interpolations (e.g. color: ${p => p.$dynamicValue} where the value comes from unbounded user input).
  • b0f3d29: React Native improvements: replaced postcss with a lightweight CSS declaration parser, fixing nanoid crashes in Expo/Metro (v6.3.* causing crashes on react-native-web - nanoid is not a function #5705) and improving parse speed 4-6x. Parent re-renders with unchanged children are 2.6-3.2x faster via cache-first render. Updated native component alias list (removed 5 dead components, added 4 missing). Added react-native as an optional peer dependency.
  • 74e8b76: Smaller install footprint via unused dependency cleanup.

@github-actions
github-actions Bot force-pushed the changeset-release/main branch 5 times, most recently from ffc7347 to 4c0c858 Compare March 19, 2026 19:27
@quantizor

quantizor commented Mar 19, 2026 •

Copy link
Copy Markdown
Contributor Author

Edit: 6.4.0 RC4 is available for testing at styled-components@test, thank you. If all looks well, please react to this message!

@quantizor

quantizor commented Mar 23, 2026 •

Copy link
Copy Markdown
Contributor Author

New prerelease published: [email protected]

npm i styled-components@test

Changes since prerelease.4:

  • Deduplicate RSC inline <style> tags across component instances via React.cache (React 19+) — reduces HTML bloat when multiple instances of the same styled component render with identical CSS

@quantizor

Copy link
Copy Markdown
Contributor Author

6.4.0-prerelease.6 published to npm i styled-components@test:

@github-actions
github-actions Bot force-pushed the changeset-release/main branch from 5cf72b3 to 858e565 Compare April 3, 2026 01:04
@quantizor

quantizor commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@wojtekmaj try [email protected] when you get a moment please!

@wojtekmaj

wojtekmaj commented Apr 3, 2026 •

Copy link
Copy Markdown

@quantizor Thanks! We're getting there, but I still managed to break it. The below code works perfectly on 6.3.12 but crashes on 6.4.0-prerelease.13:

import styled from 'styled-components';

export const Checkbox = styled.input``;

type CheckboxProps = React.ComponentPropsWithoutRef<typeof Checkbox>;

const props: CheckboxProps = {
  value: 'on',
};

<Checkbox
  ref={(ref) => {
    console.log(ref);
  }}
  // Crucial for repro: Not adding this bit causes ref to be correctly typed
  {...props}
/>;
repro.tsx:12:9 - error TS7006: Parameter 'ref' implicitly has an 'any' type.

12   ref={(ref) => {
           ~~~

On a positive note, I'm testing this on 300,000 LoC codebase, and that is the only error! I might have a better test suite than you do! 😅

@quantizor

quantizor commented Apr 3, 2026 •

Copy link
Copy Markdown
Contributor Author

@quantizor Thanks! We're getting there, but I still managed to break it. The below code works perfectly on 6.3.12 but crashes on 6.4.0-prerelease.13:

...

On a positive note, I'm testing this on 300,000 LoC codebase, and that is the only error! I might have a better test suite than you do! 😅

Looking, and I'm making regression tests for all of these so your help is super appreciated!

quantizor added a commit that referenced this pull request Apr 3, 2026
….0 compat

Split PolymorphicComponent's single callable overload into three: `as`
(required), `forwardedAs` (required), and default (no Substitute). The
default overload uses BaseProps directly, avoiding the conditional type
deferral in Substitute that blocked ref contextual typing during JSX
spread resolution (#5687).

Type performance (-22% instantiations, -12% check time):
- Variance annotations on Styled, PolymorphicComponent, IStyledComponentBase,
  IStyledStatics, CommonStatics, IStyledComponentFactory
- domElements shorthand registration cast avoids 120 redundant Styled<>
  instantiations (types already declared via mapped type on styled const)
- IStyledComponent: unconditional `& string` replaces conditional
  `R extends 'web' ? string : {}`

TS 6.0 compatibility:
- Add DOM to tsconfig lib (TS 6.0 no longer implicitly loads lib.dom.d.ts,
  causing @types/react empty element stubs to collapse all HTML types)
- Explicit rootDir in test tsconfig (TS 6.0 changed rootDir inference)
- Deduplicate @types/react via pnpm override (3 versions -> 1)
@github-actions
github-actions Bot force-pushed the changeset-release/main branch from 858e565 to eb0f491 Compare April 3, 2026 19:01
@quantizor

Copy link
Copy Markdown
Contributor Author

Fixed in 4c0b72a. The root cause was Substitute's conditional type deferring during JSX spread resolution, which blocked TypeScript's contextual typing for ref callback parameters.

The fix splits PolymorphicComponent's single callable overload into three: one for as polymorphism, one for forwardedAs, and a default that uses BaseProps directly (bypassing Substitute). The default overload handles your exact scenario — ref callback + spread props without as/forwardedAs.

@wojtekmaj your repro is now a permanent type test. Thanks for the thorough report and the 300K LoC test suite!

@wojtekmaj

Copy link
Copy Markdown

https://youtu.be/Ccoj5lhLmSQ 🤣

@quantizor

Copy link
Copy Markdown
Contributor Author

@wojtekmaj please try [email protected] when you get a chance. Typechecking should be a little faster as well.

@wojtekmaj

Copy link
Copy Markdown

@quantizor Tested 15 apps, 8 web, and 7 native, all green!

@quantizor

Copy link
Copy Markdown
Contributor Author

@quantizor Tested 15 apps, 8 web, and 7 native, all green!

@wojtekmaj Thank you!! You've seriously been so helpful with debugging this release, very much appreciated.

@github-actions
github-actions Bot force-pushed the changeset-release/main branch from 21386f8 to 5d8fb16 Compare April 5, 2026 18:22
@laurenskling

Copy link
Copy Markdown

I've had this weird bug in prerelease.10+ and I found the reason now. Styles are dropped, after a refresh or hmr (which I don't know why that is), for restyles of a originally rule-less SC. For example:

const Button = styled.div``;

export default styled(Button)`
  background-color: green;
`;

This div will not have a background color, unless you put some rule inside of the Button.

@laurenskling

laurenskling commented Apr 5, 2026 •

Copy link
Copy Markdown

So in the new version, all my RSC styles are supposed to be inline <style> tags, correct? With this change, the Elements tab bubbles full of duplicate style rules. Here's my:

I have a component that accepts 3 props. It outputs different css based on those props, just like we loved to do for all these years. In this new version, a style tag is created for each possible output. Meaning shared css, outside of the prop checking, is added multiple times to all those style tags. Resulting in my styles tab bubbling full of the same rules:

export default styled.li<{ $someprop?: boolean }>`
  position: relative;
  ${({ $someprop }) => $someprop && css`
    position: static;
  `}
`;

(.lhACiT have $someprop) Scherm­afbeelding 2026-03-31 om 11 26 22

Scherm­afbeelding 2026-03-31 om 11 25 45 It's not bug, it's a feature. Do we want it?

I know you've suggested to move away from props checking styling in RSC, but until we do...

This seems fixed in .14. I hadn't seen any specific changelogs to it, but you did fix it? Nice :)

I see now, they result to different classNames now, so no longer pointing to the same thing over and over.

@github-actions
github-actions Bot force-pushed the changeset-release/main branch 2 times, most recently from cbf1a58 to d191704 Compare April 9, 2026 15:26
@github-actions
github-actions Bot force-pushed the changeset-release/main branch from d191704 to f1b1e4c Compare April 9, 2026 15:30
@quantizor
quantizor merged commit bf65d5d into main Apr 9, 2026
@quantizor
quantizor deleted the changeset-release/main branch April 9, 2026 15:43
@rafaell-lycan

Copy link
Copy Markdown

@quantizor could you generate a mini benchmark comparing this version with Emotion and perhaps Linaria?

Anywho, this update is great news for those who are still on Styled Components and can't migrated.

Thanks a lot 🙏

@quantizor

Copy link
Copy Markdown
Contributor Author

@quantizor could you generate a mini benchmark comparing this version with Emotion and perhaps Linaria?

Anywho, this update is great news for those who are still on Styled Components and can't migrated.

Thanks a lot 🙏

Here is the most recent one I posted on Twitter: https://x.com/quantizor/status/2037541158222463014?s=46 (the workspace version is sc 6.4)

They're here in the repo in the benchmarks package if you want to experiment! Don't have one for Linaria but Emotion is in there.

quantizor added a commit that referenced this pull request Apr 28, 2026
…ibrary files

Pass two of the comment-discipline cleanup, covering the files that the
first pass didn't reach: types.ts, parser/{parser,emit-web,emit-fast},
utils/{cssCompile,rsc,rscSelectorRewrite}, native/responsive,
constructors/createTheme, models/ThemeProvider.

The cuts focus on:

- One-line JSDoc that restates the function/type signature.
- Visual-section separators (`// ---------- foo ----------`) that don't
  earn their keep when sections are short.
- Multi-paragraph design rationale that drifted into narration.
- "Used by X / corresponds to Y" pointers that rot when callers move.
- Aspirational notes ("would love to figure out...") and historical
  references ("learned from markdown-to-jsx") that aren't load-bearing.

Kept: brief WHY pointers for non-obvious constraints (CSS escapes,
hash stability, Jest teardown, paste-artifact resilience, RSC platform
differences), upstream-issue references (#5687, #5730), and public API
docs that include the usage example consumers actually need.

No behavior change: 1087 main + 285 native tests pass, types clean.
quantizor added a commit that referenced this pull request Jun 2, 2026
…get completion survives mid-typing

A partially-typed or unknown attribute on a polymorphic styled component
(e.g. <Comp as="video" foo l|>) matched none of the call overloads, so
overload resolution failed and JSX attribute completion dropped to nothing
-- the as-target's props (video's loop/controls/...) disappeared while
typing. Replacing the overload set with a single conditional call signature
keeps completion resolved at all times.

The branching (PolymorphicCallProps) preserves prior behavior: a real
as-target substitutes its props; no-as / wrapped-as (Url-typed) keeps
Substitute-free base props for ref inference on spread (#5687), wrapped-as
assignability (#5734), and plain completion (#5741); forwardedAs substitutes
the forwarded target.

The single signature instantiates a conditional per JSX usage where the
overload set resolved plain usage to a free non-generic overload, so some
extra type work is inherent. Two changes keep it small: the target test uses
string | AnyComponent rather than the literal-heavy WebTarget (same set,
~6% fewer instantiations across call sites), and the no-target result is a
shared alias so it instantiates once. Net vs the prior overloads:
instantiations 1,608,782 -> 1,696,358 (+5.4%), check time 2.94s -> 3.22s.
quantizor added a commit that referenced this pull request Jun 2, 2026
…arget autocomplete while typing (#5758)

* fix(types): keep styled() and .attrs() permissive for un-introspectable targets

Wrapping a component whose props can't be statically read -- most notably
Mantine v7's polymorphic-factory components (Button, Card, Menu.Item),
whose generic callable signature defeats React.ComponentPropsWithRef and
collapses to {} -- made the resulting styled component reject every prop,
including children, at the JSX call site and via .attrs().

Detect the un-introspectable case and widen to a permissive prop bag for it
alone; targets with readable prop types keep full checking. The widening is
confined to the JSX call surface, never the statics or defaultProps, so the
real Props can't leak past the call site. The "no known keys" test is
distributed over the prop type first so a bare union of disjoint shapes
(keyof intersects to never despite being introspectable) isn't widened by
mistake.

Closes #5756

* fix(types): collapse polymorphic overloads to one signature so as-target completion survives mid-typing

A partially-typed or unknown attribute on a polymorphic styled component
(e.g. <Comp as="video" foo l|>) matched none of the call overloads, so
overload resolution failed and JSX attribute completion dropped to nothing
-- the as-target's props (video's loop/controls/...) disappeared while
typing. Replacing the overload set with a single conditional call signature
keeps completion resolved at all times.

The branching (PolymorphicCallProps) preserves prior behavior: a real
as-target substitutes its props; no-as / wrapped-as (Url-typed) keeps
Substitute-free base props for ref inference on spread (#5687), wrapped-as
assignability (#5734), and plain completion (#5741); forwardedAs substitutes
the forwarded target.

The single signature instantiates a conditional per JSX usage where the
overload set resolved plain usage to a free non-generic overload, so some
extra type work is inherent. Two changes keep it small: the target test uses
string | AnyComponent rather than the literal-heavy WebTarget (same set,
~6% fewer instantiations across call sites), and the no-target result is a
shared alias so it instantiates once. Net vs the prior overloads:
instantiations 1,608,782 -> 1,696,358 (+5.4%), check time 2.94s -> 3.22s.
quantizor added a commit that referenced this pull request Jul 19, 2026
Replace the three PolymorphicComponent overloads with a single call
signature backed by a twin-conditional PolymorphicCallProps, so JSX
attribute completion no longer collapses mid-typing after as=. Preserves
ref-callback inference on spread props (#5687), wrapped-as assignability
(#5734), and plain-usage prop completion (#5741).
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

4 participants