Skip to content

fix(types): keep union props through styled(), and stabilize the hook sequence - #5789

Merged
quantizor merged 3 commits into
6.xfrom
fix/6.5-hook-order-and-union-props
Aug 6, 2026
Merged

quantizor merged 3 commits into
6.xfrom
fix/6.5-hook-order-and-union-props

Conversation

@quantizor

Copy link
Copy Markdown
Contributor

Closes #5787. Also addresses #5788, with a correction to its stated cause (below).

Union props survive styled() again (#5787)

A component typed ButtonProps | AnchorProps stopped accepting href once wrapped, accepting only the props common to every member of the union.

OverrideStyle used to test P extends { style?: infer S }, a naked type parameter, which distributes over a union for free. #5784 rewrote the test as 'style' extends keyof P, which inspects P rather than checking it, and distribution went with it. keyof a union is the keys common to every member, so an undistributed pass rebuilt A | B from the shared keys alone. Restored with an outer P extends unknown.

The same bug, one seam over

Auditing the siblings turned up a second instance that predates 6.5.0. Substitute and MergeProps recognize an empty prop bag with keyof B extends never, and a union of disjoint shapes satisfies that too, so the fast path dropped it wholesale:

const Box = styled.div<{ onlyA: string } | { onlyB: number }>``
<Box onlyA="x" />   // rejected: both members' props were gone

Now discriminated with {} extends B, which an empty bag satisfies and a union of required-key members does not. The complete fix (re-asking keyof per member) is measured as fatal: it tips tsc into TS2589 against a caller spreading as?: WebTarget, because the added distribution nests inside the one the polymorphic signature already performs over that ~153-member union. The residue, an all-optional disjoint union, is pinned in the contract suite as a known limitation rather than left silent.

Hook sequence (#5788)

useDebugValue sat inside the render cache's miss branch, so it ran on a cache miss and was skipped on a cache hit. Moved past the if/else. The use-prefixed useInjectedStyle wrapper it lived in called no hooks of its own, so it is inlined; the seam that made a conditional call look safe is gone.

Correction to the issue's stated cause. #5788 attributes a Rendered fewer hooks than expected crash to this call. It cannot produce that error. In React 19.2.3 the throw is guarded solely by currentHook !== null && currentHook.next !== null, and useDebugValue only feeds hookTypesDev, which backs a warning; useContext allocates no slot either. A 6.4.x styled component therefore has exactly one hook slot (useRef) where 6.3.12 had none, and going from one slot to zero cannot trip that condition. A MUI DataGrid + @mui/styled-engine-sc + React 19.2.8 reproduction did not crash, with or without StrictMode. This change is still correct, but the reporter's crash is unexplained and I would keep #5788 open pending a runnable repro.

Guardrails

  • Contract-suite cases across every union surface (plain, as, forwardedAs, .attrs, chained, disjoint). Every accepted prop is paired with a rejected one, so a transform that widened props to an index signature cannot pass the section with the union destroyed.
  • A runtime test that records the hook sequence by wrapping React's own use* exports and asserts cache-hit and cache-miss renders match. It picks up any hook added to the render path later without being told about it.
  • A unionTarget kind in the consumer type-check fixture. The budget existed to catch exactly this class and missed it because no fixture component had union props. It now prices the distributive path and, since the run fails on any fixture compile error, fails outright if the union collapses again.

Each guardrail was validated red against the unfixed code before being kept.

Cost

+0.04% instantiations, types and memory flat. The recorded budget moved because the fixture grew, not because the cost did.

Docs

Separate first commit: AGENTS.md had grown to hold both the rules and every subsystem's full specification, so it is now the rules plus a map, with one home per subject under docs/. Tracing the moved text against the source corrected six claims that no longer described 6.x, including a keyframes section describing v7 behavior and citing a symbol absent from this branch.

AGENTS.md had grown to carry both the rules and the full specification of every
subsystem, so the rules were hard to find and the specifications drifted unread.
It now holds the rules and a map; each subject has one home under docs/.

Tracing the moved text against the source turned up several claims that no
longer described 6.x:

- keyframes were documented as emitted in a dedicated <style> tag that component
  CSS must never be prepended to. 6.x concatenates them into one tag, and the
  cited getEmittedCSS does not exist on this branch.
- stylisPluginRSC was documented as rewriting child-index selectors. It also
  expands adjacent sibling combinators, with its own limitations.
- IS_BROWSER checks document as well as window.
- nonce was documented as inherited by a nested StyleSheetManager. It is a sheet
  option resolved by getNonce, and is not part of the RSC context override.
- createTheme's contract omitted GlobalStyle, without which nothing is emitted.
- the stylis AST caveat said props "can alias" between a rule and its nested
  copy. The parser hands the nested ruleset the parent's array outright, which
  is now stated with the reproduction.

CLAUDE.md was a real symlink to AGENTS.md and is now a pointer file, so writing
either name cannot clobber the other.
… sequence

Three fixes plus the guardrails that keep each from recurring.

`OverrideStyle` lost its distribution over unions when #5784 moved the test from
a naked `P extends { style?: infer S }` to `'style' extends keyof P`. `keyof` a
union is the keys common to every member, so an undistributed pass rebuilt
`A | B` from the shared keys alone and dropped every member-specific prop.
Restored with an outer `P extends unknown`. Fixes #5787.

The same class, found while auditing the siblings: `Substitute` and `MergeProps`
recognize an empty prop bag with `keyof B extends never`, which a union of
disjoint shapes also satisfies, so such a union was dropped wholesale. Now
discriminated with `{} extends B`. Predates 6.5.0. A per-member re-ask is the
more complete fix and tips tsc into TS2589 against a caller spreading
`as?: WebTarget`; the accepted limitation, an all-optional disjoint union, is
pinned in the contract suite.

At runtime, `useDebugValue` sat inside the render cache's miss branch and was
skipped whenever props were unchanged. Moved past the if/else. The `use`-prefixed
`useInjectedStyle` wrapper it lived in called no hooks of its own and is inlined,
removing the seam that made a conditional call look safe.

Guardrails: contract-suite cases for every union surface, each accepted prop
paired with a rejected one so a widening cannot fake a pass; a runtime test
asserting the hook sequence is identical across cache hit and miss; and a
`unionTarget` kind in the consumer type-check fixture, which prices the
distributive path and, because the run fails on any fixture compile error, fails
outright if the union collapses again.

Consumer type-check cost: +0.04% instantiations, types and memory flat. The
recorded budget moved because the fixture grew, not because the cost did.
Copilot AI lite review requested due to automatic review settings August 6, 2026 15:28
@changeset-bot

changeset-bot Bot commented Aug 6, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: 23efda0

The changes in this PR will be included in the next version bump.

This PR includes changesets to release 1 package
Name Type
styled-components Patch

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

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Fixes TypeScript prop-type regressions involving union-typed props flowing through styled() and strengthens runtime correctness by ensuring the render-cache hit/miss split does not change the React hook sequence. It also adds guardrails (type contracts + perf fixture + a runtime hook-sequence test) and moves internal specifications out of AGENTS.md into dedicated docs/ files.

Changes:

  • Restore distributive behavior in the type-level style override so union member-specific props survive styled() wrapping.
  • Fix an older union edge case where disjoint union prop bags could be mistaken for “empty” and dropped by Substitute/MergeProps.
  • Stabilize the debug hook call-site across render-cache hit/miss, and add tests + perf fixture coverage to prevent regressions.

Reviewed changes

Copilot reviewed 21 out of 22 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
packages/styled-components/type-perf.budget.json Updates committed type-perf budget numbers to match the expanded fixture.
packages/styled-components/src/types.ts Makes OverrideStyle distribute over unions again; hardens Substitute/MergeProps empty-bag guard against disjoint unions.
packages/styled-components/src/test/types.tsx Adds compile-time contract cases for union targets, disjoint unions, and documented limitations.
packages/styled-components/src/test/memoization.test.tsx Adds a runtime test asserting identical hook sequences across render-cache hit/miss renders.
packages/styled-components/src/models/StyleSheetManager.tsx Updates spec reference in comment to the new docs location.
packages/styled-components/src/models/StyledComponent.ts Moves useDebugValue out of the cache branch and removes the now-unnecessary wrapper function.
packages/styled-components/src/constructors/constructWithOptions.ts Updates inline comment to reference the new type-performance spec doc.
packages/styled-components/scripts/typePerf.mjs Adds a unionTarget fixture kind and ensures member-specific props are exercised in perf runs.
docs/type-performance.md New spec doc describing the type-perf budget, fixture intent, and load-bearing type-shapes.
docs/type-contracts.md New spec doc describing the compile-only type contract suites and how to write/read them.
docs/runtime-performance.md New spec doc capturing measured runtime performance patterns and render-cache constraints.
docs/rsc-style-injection.md New spec doc describing RSC style emission/injection behavior and constraints.
docs/global-styles.md New spec doc describing GlobalStyle’s shared-group architecture and lifecycle constraints.
docs/create-theme.md New spec doc describing the createTheme contract and usage model.
docs/build-architecture.md New spec doc describing build flags, server detection, and native entry isolation constraints.
docs/attrs.md New spec doc describing attrs precedence and its escape hatch.
AGENTS.md Refactors to be rules + an index of spec documents, removing embedded subsystem specifications.
.changeset/union-props-survive-styled.md Adds a patch changeset for union-prop preservation through styled().
.changeset/stable-hook-sequence.md Adds a patch changeset for stable React DevTools debug value reporting across renders.
.changeset/disjoint-union-props.md Adds a patch changeset for disjoint-union prop-bag preservation.

💡 Add Copilot custom instructions for smarter, more guided reviews. Learn how to get started.

Comment thread docs/type-performance.md Resolved
Comment thread .changeset/disjoint-union-props.md Resolved
Reset the hook recorder's buffer in a finally so a throwing render cannot leave
it live for the next one. Drop the hard-coded instantiation counts from the
type-performance doc and point at the budget file and its command instead, per
the project's rule against restating drift-prone numbers. Rewrite both changesets
in terms of what a consumer observes rather than the type expressions involved.

Copilot AI left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Pull request overview

Copilot reviewed 21 out of 22 changed files in this pull request and generated no new comments.

@quantizor
quantizor merged commit a0a92cd into 6.x Aug 6, 2026
8 of 14 checks passed
@quantizor
quantizor deleted the fix/6.5-hook-order-and-union-props branch August 6, 2026 23:04
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.

2 participants