Repository navigation
Conversation
Prior to v6 this built a new object `propsForElement` with only the forwarded props. Since v6, it changed to mutating `context` in place, see 0b8605a The new approach keeps the props but sets them undefined. This makes React emit errors in dev and test. Delete them from the context instead. Additionally check and delete any undefined values in context, for example if `.attrs()` sets some to undefined, they should be removed at this point.
This is how it used to work in v5. The earlier attempt to optimize by modifying context directly failed because we have to delete anyway. May as well build the new props object instead.
agriffis
force-pushed
the
v6/dont-send-undefined-props-to-dom
branch
from
October 18, 2022 15:54
7a302f9 to
7d6cf6e
Compare
1 task
Closed
1 task
quantizor
added a commit
that referenced
this pull request
Sep 25, 2026
…on older React, build guards (#5822) * fix: drop stray process reference from the browser build (#5819) The dev-only emit-count cache checked NODE_ENV before IS_RSC. The browser build replaces IS_RSC with false, so both ternary branches folded to null and the minifier kept a bare `process;` statement, which throws ReferenceError in browsers without a process polyfill. Lead with IS_RSC so the browser build drops the expression, and guard the class in treeshake.test.ts: browser bundles may read `process` only as `typeof process` or `process.env`. * docs: correct createGlobalStyle RSC dedup comment after #5808 The comment pointed at StyledComponent's per-render dedup pattern, which #5808 replaced with per-instance emission. createGlobalStyle keeps its dedup (documented behavior); describe that directly instead of cross-referencing a pattern that no longer exists. * docs: drop stale RSC dedup claim from the FAQ Since #5808 each styled component instance emits its own style tag in server components, so styles are no longer deduplicated per render. * fix: strip // line comments from native inline style declarations (#5613) Web (packages/styled-components/src/utils/stylis.ts) already handles both repros from #5613 correctly on this branch: stylis 4.3.6's own tokenizer strips // line comments natively, independently of styled-components' preprocessCSS. Verified with two new end-to-end regression tests in src/test/styles.test.tsx that reproduce the exact issue snippets (a multiline calc() with interpolations, and a trailing comment followed by a nested component-selector block); both pass even with preprocessCSS's own // handling fully disabled or bypassed. No web-side change needed. The native inline-style path (src/models/InlineStyle.ts) never had this support: its stripComments() only stripped /* */ block comments, so a // comment left in a React Native styled-components template was parsed as literal text and could corrupt or drop the declaration(s) after it on the same line. Added a paren-depth-aware stripAllComments() that also strips //, routed to only when a template actually contains //, so the existing block-comment-only fast path is untouched. A // immediately preceded by `:` is left alone so a bare, unquoted URL scheme outside of url()/quotes (e.g. --api-url: https://host/path) isn't mistaken for a comment start. Added a bench case (CSS_WITH_LINE_COMMENTS) to src/bench/native.test.tsx: the new path costs the same as the existing block-comment path, and the no-comment and block-comment-only cases are unaffected (within run-to-run noise) versus the pre-fix baseline. * fix: correct component name typo in the useTheme error example * chore: remove unused removeGlobalStyleTag * docs(types): state the minimum @types/react and gate it in the dist type check (#5760) * feat: warn in development when server and browser styled-components versions differ (#5737) * build(deps): patch vulnerable tooling dependencies Bump next to ^16.3.3 in the sandbox to clear two critical RCE advisories (<16.3.3). Raise the brace-expansion override floor to >=2.1.4 (DoS fix), verified safe since every current consumer (minimatch 3.x and 9.x) already resolves through the existing >=2.0.2 override. Add scoped overrides for the remaining flagged transitives (shell-quote, fast-xml-builder, @babel/plugin-transform-modules-systemjs, js-cookie, ws, js-yaml, fast-uri, postcss, nanoid, browserslist, joi, baseline-browser-mapping, postcss-selector-parser), each bounded to stay within the major its parent already expects. ws and js-yaml get per-major selectors (ws@6/7/8, js-yaml@3/4) since multiple majors are resolved simultaneously across the tree. Bump @babel/core to ^7.29.7 (minor, within range) to clear its low sourcemap-read advisory. decode-uri-component and image-size are left unpatched: their fixed versions changed the CJS export from a callable default to a named-exports object, which breaks source-map-resolve's and metro's direct require(...)(input) call pattern respectively. Confirmed by unpacking both old and new tarballs and comparing require() shapes. * fix(types): declare the @types packages the published declarations import dist/**/*.d.ts imports React's types, react-dom/server's PipeableStream, and the NodeJS stream globals, none of which the package declares. Add @types/react, @types/react-dom and @types/node as optional peer dependencies with a "*" range rather than a floor, since a floor would make npm fail installs with ERESOLVE for anyone below it and this ships as a patch on an already-released major. @types/stylis is not added: none of the dist .d.ts files import '@types/stylis' by name (they import from 'stylis' directly, which carries no bundled types of its own), and @types/stylis is currently only a devDependency, so it does not reach consumers either. Noted as a finding for the coordinating session, not resolved here. * test: guard browser bundles against other Node-only globals Extends the #5819 build check to Buffer, global, __dirname, __filename and setImmediate, which throw the same way as a bare process reference in a browser without polyfills. * docs(agents): hold GitHub comments to the consumer-facing rule * docs(agents): no comments on dependabot PRs * fix: emit RSC global styles per instance so they survive Suspense reveals and navigation createGlobalStyle deduped RSC <style> tags across a request via a React.cache-scoped Set, keyed on the static componentId+stylis hash or the dynamic CSS string. That ledger carries the same Suspense hazard #5808 removed for styled components: a Suspense fallback renders before the resolved content, so the fallback's global style wins the ledger and the resolved instance emits nothing; React then discards the fallback (tag and all) on reveal, leaving the page with no global styles at all. With synchronous content the fallback is never even in the HTML, so the global goes missing with JavaScript off too. An async layout and its page both rendering the same global hit a third variant: the page wins the ledger, and a later client-side navigation to a sibling page removes the only tag, since the layout that still needs it never re-renders. Every server-rendered instance now emits its own <style data-styled-global> tag, with no shared ledger. Byte-identical duplicates cost about a byte each under gzip within its 32 KB window; farther apart, each costs roughly the gzipped size of the CSS on its own, and brotli stays near zero either way thanks to its larger window. * fix: apply attrs defaults over explicit undefined props and forward undefined to wrapped components (#5807, #4338) * fix(native): strip block comments inside parentheses when line comments are present stripAllComments checked paren depth before checking for a /* */ block comment, so once the input also contained a //, any block comment inside a function call (calc(), etc.) was copied through unstripped instead of removed. stripComments (the path used when no // is present) already stripped these unconditionally. Move the block-comment check above the paren-depth branches so both paths agree. * docs(types): correct the search tag changeset and comment domElements.ts's SupportedHTMLElements comment claimed styled.search "keeps working via the WebTarget string overload" on old @types/react, which is wrong for property access: styled.search is a key of a mapped type built from this union, so dropping 'search' from it makes styled.search itself a compile error there. Only styled('search') (the function-call form) goes through WebTarget's general string overload. Correct the comment, and correct the exact affected range in the search-tag changeset: @types/react added <search> to React.JSX.IntrinsicElements in 18.2.12 (confirmed against the published tarballs), so the gap is 18.2.6 (the documented floor) through 18.2.11, not "18.2.6 and nearby early 18.2.x patches". Add test-types/intrinsic-elements-index-signature.tsx (wired into test:types via its own tsconfig, matching template-index-signature.tsx's isolation pattern) covering a consumer that globally augments React.JSX.IntrinsicElements with a string index signature: keyof such an interface is `string`, and Extract<T, string> must still return T unchanged when every member of T is a string literal, so SupportedHTMLElements keeps every tag and TargetProps for a known tag must not widen to any. Confirmed red (TS2578 on both @ts-expect-error presence anchors) against a naive keyof React.JSX.IntrinsicElements without the Extract against the runtime tag list. Measured the Extract's own type-perf cost against its pre-#5760 parent (a plain union, rebuilt via a temporary revert of just this file): +6 types (+0.016%) and +1,532 instantiations (+0.207%) on the 100- component consumer fixture, memory unchanged. Within noise; kept as-is, no budget update needed. * fix: clarify the server and browser version mismatch warning A page can legitimately host two apps on different styled-components versions (a micro-frontend setup), so the warning must not assert failure as a certainty. Reword it to describe what was found and let the reader judge whether it applies, and name the same-app case explicitly as the one where it matters. Updated the matching test and changeset to the new wording. * fix(types): declare @types/stylis as an optional peer The emitted .d.ts files (stylisPluginRSC.d.ts, stylis.d.ts, StyleSheetManager.d.ts) import Middleware from 'stylis', all type-only, and stylis ships no types of its own. @types/stylis was only a devDependency, so a strict consumer (an isolated node_modules layout, skipLibCheck off) fails to resolve it: reproduced in isolation with a type-only import against a stylis install with no @types/stylis anywhere in the resolution chain (TS7016). Declared it as an optional peer, alphabetized with the existing @types/* entries, and extended the declare-types-peers changeset to cover it. pnpm install left the lockfile unchanged, since the existing devDependency already satisfies the new peer. * chore: stop tracking the generated sandbox next-env.d.ts packages/sandbox/next-env.d.ts matches the root .gitignore's **/next-env.d.ts pattern and is rewritten by every next build; it was only tracked because it predates that pattern being added. * fix(types): ship @types/stylis as a dependency instead of @types peers Declaring @types/node, @types/react, @types/react-dom and @types/stylis as optional peers forked the package's install identity under pnpm: a resolved optional peer is part of the .pnpm directory key, so two workspace projects on different @types/node versions each got their own physical copy of styled-components (two module instances, an unshared ThemeProvider context). Reproduced on pnpm 10 with a two-project workspace against a packed tarball: two styled-components entries in node_modules/.pnpm before, one after. All four peers and their meta entries are removed and the peers changeset is deleted. The one type package the published declarations cannot get from the consumer is @types/stylis: stylis is a pinned regular dependency that ships no types, and StyleSheetManager.d.ts and stylisPluginRSC.d.ts import from it. It moves from devDependencies to dependencies at 4.2.7 (the newest release, matching stylis 4.x). Regular dependencies do not enter the install identity. The rule and its reason live in docs/build-architecture.md. Two build tests guard it: no @types package in peerDependencies, and every untyped regular dependency the emitted .d.ts files import carries a matching-major @types package as a regular dependency. * fix(types): type the server stream structurally and gate React 16/17 types dist/models/ServerStyleSheet.d.ts imported PipeableStream from react-dom/server, which @types/react-dom 16 and 17 do not export, so the published types failed with TS2305 under skipLibCheck: false on those majors (and TS7016 for a project with no @types/react-dom at all). The parameter now uses a local structural type with the one member read, `pipe`, in React's exact generic signature, so React 18 and 19 callers passing renderToPipeableStream's result are unaffected. A contract case pins that, with a negative anchor. test:types:dist gains React 16 (16.14.41 + react-dom 16.9.19) and 17 (17.0.59 + react-dom 17.0.20) floor targets, each react-dom being the newest of its major published before the matching react floor. Both floors are the first patch carrying React.JSX (16.14.40 and 17.0.58 have only the global namespace). It also compiles a consumer fixture, test-types/published-types-consumer.tsx, through the built dist on every target. The script now reads diagnostics from the compiler API instead of parsing tsc text, which closes three silent passes, each reproduced against the previous script before the rewrite: - a diagnostic with no file (TS2688 missing type library, TS5023 unknown option) was dropped by the .d.ts-line filter and the run passed; it now fails. - a cached isolated install was reused whenever it existed, so a changed pin silently tested the old version; it now reinstalls on any version mismatch and fails if npm still installs the wrong one. - tsc printed paths relative to the caller's cwd while the filter resolved them against the package root, so running the script from the repo root passed a broken dist; attribution is now by absolute file name. It also verifies every @types/react file in each program came from the target's own folder (an unmapped react/jsx-runtime pulled the root 18.3 copy in alongside the target), and drops stale target folders. * fix(types): keep styled.search on every @types/react with a fallback bag SupportedHTMLElements had been narrowed to the tags the consumer's @types/react declares, which removed styled.search from the types (TS2339, even under skipLibCheck: true) on every 16.x and 17.x and on 18.2.6-18.2.11, none of which declare a <search> intrinsic. It is the full runtime tag list again. A tag the consumer's version does not declare now resolves to UndeclaredTagProps, DetailedHTMLProps<HTMLAttributes<HTMLElement>, HTMLElement>, the shape 18.2.12+ declares for <search>: - TargetProps gains a third, false-branch arm for SupportedHTMLElements members, widened like a declared tag; declared tags and components never reach it, and custom-element strings still fall through to {}. - The .attrs() redirect seam routes ComponentPropsWithRef through KnownTargetPropsWithRef, which tests T extends React.ElementType per member inside the existing KnownTarget distribution. That removes the TS2344 the full union otherwise puts in constructWithOptions.d.ts under skipLibCheck: false. Measured with the Extract-era dist as baseline (TS 5.9.3, pinned @types/react 18.3.28): type-perf 36,892 to 36,898 types, 739,867 to 738,363 instantiations, 193 MB flat; type-perf:augment 37,051 to 37,057 types, 814,212 to 812,708 instantiations, 194 MB flat. A three-layer function-form .attrs redirect chain measured +0.93% instantiations with no TS2589. Contract coverage: the published-types consumer fixture exercises styled.search, styled('search'), as="search" and .attrs({ as: 'search' }) with negative anchors on all five dist targets (red on 16, 17 and 18.2.6 before this: TS2339, the two catch-all anchors unused, and the redirect rejected), and the pinned suite asserts UndeclaredTagProps is identical to the declared <search> props. The decision and rejected alternative are in docs/type-performance.md. * docs: point the type dependency rules at the build test that enforces them * fix(types): keep undeclared-tag props permissive on older @types/react On an @types/react that lacks a tag's JSX intrinsic (<search> on every 16.x and 17.x and on 18.2.6-18.2.11), styled.search, styled('search') and an .attrs({ as: 'search' }) redirect shipped permissive: the tag falls through TargetProps to {} and takes the un-introspectable bag. The typed HTMLElement fallback narrowed that in a patch, so it is backed out: - TargetProps drops its third arm; UndeclaredTagProps and UndeclaredIntrinsicProps are gone. - KnownTargetPropsWithRef keeps lifting ComponentPropsWithRef's ElementType constraint (no TS2344 in constructWithOptions.d.ts) but returns {} for an undeclared tag, which is exactly what ComponentPropsWithRef itself resolves it to (verified identical on 16.14.41). The full tag union stays, so styled.search exists on every version. as="search" is unchanged and still rejects unknown props. Contracts: the consumer fixture now pins that each of the three forms accepts any prop exactly where the intrinsic is missing (red on 16, 17 and 18.2.6 against the typed dist), with a custom-element control that is permissive everywhere and a div control that never is, plus the as="search" negative anchor. The pinned suite asserts KnownTargetPropsWithRef is identical to ComponentPropsWithRef for a declared tag, a tag union and a component. type-perf against the previous tip: 36,898 to 36,886 types, 738,363 to 738,335 instantiations, 193 MB flat; augmented 37,057 to 37,045 types, 812,708 to 812,680 instantiations, 194 MB flat. docs/type-performance.md records the rule (never narrow these fallbacks in a non-major) and the typed bag as the preferred next-major direction. * fix: keep caller-passed undefined props when attrs spreads them back An identity-spread attrs function (attrs(({ type = 'button', ...rest }) => ({ type, ...rest }))) echoes a caller's own explicit undefined prop back through its return value for every key it doesn't touch. resolveContext treated that echoed undefined the same as an attrs-authored one and deleted the key, so a prop like onClick={undefined} never reached a wrapped component even though it would have with no attrs at all. Only clear a key when context held a defined value before this attrs call; if context already held undefined (the caller's own value, echoed straight through), leave it in place so it stays forwardable. Implemented without ever calling `delete` on the context object: removing a key mid-object flips it to V8 dictionary mode and slows every subsequent for..in read for the rest of the render (docs/runtime-performance.md), so a cleared key is assigned undefined and recorded in a small side list that buildPropsForElement consults instead. Same fix on the native render path (StyledNativeComponent.ts). Also stopped calling isTag() twice per web render (buildPropsForElement and the class/className assignment): it reads process.env.NODE_ENV at runtime in the unbundled dist and under Jest, so a repeat call doubled that cost for no benefit. * perf: guard the attrs render path against dictionary-mode context Adds bench scenarios (src/bench/web.test.js) covering the two per-render costs the previous commit removed: an attrs function clearing a real, ever-changing caller-supplied prop (the delete-vs-assign path), and a caller passing an explicit undefined prop to a DOM tag and to a wrapped component (the isTag call-count path). Measured on this worktree, tip b9e65ce vs the fix, 5 runs each, alternating order (median, 1K children cycling colors): - attrs clears a real prop: 675.8ms baseline vs 505.6ms fixed (1.34x) - explicit undefined to a DOM tag: 587.0ms baseline vs 537.4ms fixed (1.09x) - explicit undefined to a wrapped component: 628.1ms baseline vs 632.6ms fixed (no measurable difference; isTag short-circuits on `typeof target === 'string'` before reading process.env for a non-string target, so the removed second call was already nearly free there) Also documents both gotchas in docs/runtime-performance.md so they don't recur: never delete from the render context, and a helper that reads process.env must not be called more than once per render for the same input. * docs: spell out the attrs and undefined prop behavior changes Bounds the first behavior change to the 6.3.12 through 6.5.x line instead of an open-ended "since 6.3.12", now that the fix lands. Names the consumer-visible impact of the second behavior change ('x' in props checks and {...defaults, ...props} merges) and corrects which release regressed it. Verified against git history: the omit-all-undefined-values line in buildPropsForElement traces to bb57780 (PR #3839), present as early as the v6.0.0 beta line, not 6.1.14 as originally suspected -- 6.1.14's only change to this area was an unrelated ref-forwarding fix (18ebf6d). Wrote "since v6.0" rather than the disproven version. * fix(native): keep protocol-relative values that follow a colon stripAllComments only skipped `//` as a comment start when the single character immediately before it was `:`, so a value like `--cdn: //cdn.example.com/x.png` (colon, then a space, then the protocol-relative URL) still had its `//` treated as a JS-style line comment, corrupting the declaration. Walk back past whitespace to find the nearest preceding non-whitespace character instead, so a colon followed by any amount of space still counts as "a value just started". Also rewrote both stripComments and stripAllComments to copy whole runs between comment boundaries (substring) instead of one character at a time, and to return the original string unchanged when no comment was actually removed (e.g. a `/*` or `//` that only ever appears inside a quoted string or a url()). Bench (parseCSSDeclarations throughput, 2 runs before/after, 100K iterations each): - complex (20 decls, quotes, parens, comments): 498ms/509ms before, 324ms/268ms after - with comments (6 comments, 6 declarations): 181ms/182ms before, 138ms/110ms after - with // line comments (6 comments, 6 declarations): 180ms/181ms before, 143ms/118ms after - simple/medium (no comments at all) and empty string: unchanged, as expected, since those already returned before reaching either rewritten function .changeset/native-line-comments.md still accurately describes what it covers (scheme URLs, not protocol-relative ones), so left as is. * fix: ignore browser-created style tags in the version mismatch warning warnOnVersionMismatch queried every style[data-styled] tag, but dom.ts's makeStyleTag stamps data-styled-version on browser-created "active" tags too. Two client copies of styled-components at different versions on the same page each create their own active tag at their own version, so one copy would see the other's active tag, mistake it for a stale server-rendered tag, and print "Found server-rendered styles..." even though nothing was server-rendered. That scenario is a live, same-page version mismatch, already covered by the separate multiple-instances warning in base.ts. Skip any tag whose data-styled value is SC_ATTR_ACTIVE before checking its version. * docs: align RSC emission docs and comments with the per-instance rule Corrects the compression claim in .changeset/rsc-suspense-style-removal.md to match docs/rsc-style-injection.md: identical rules only compress away almost for free within gzip's 32 KB back-reference window; farther apart, each repeat costs roughly its own gzipped size, and brotli stays cheap regardless of distance. Points the StyledComponent.ts comment near the RSC emission branch at that same spec section instead of restating the fact inline. Removes history narration from docs/rsc-style-injection.md, in favor of stating the current constraint directly, with the three createGlobalStyle Suspense failure modes as a list rather than a run-on sentence. Corrects the three RSC test files' "needed for RSC dedup" header comment: React.cache backs StyleSheetManager's per-render reset in all three, and additionally the redundant-emit-tag counter in styled.rsc.test.tsx; there is no dedup ledger anymore. Rewrites createGlobalStyle.rsc.test.tsx's "previously deduped" test comment as the current per-instance-emission rule rather than a history note. Left two other grep hits from the previously/was-removed/used-to sweep alone after reading them in context: native.test.tsx's "used to break" is CSS-comment fixture text being parsed by the test, not a doc comment, and StyledComponent.ts's "is used to preserve" is the auxiliary-verb sense, not narration. * feat: warn when one global style repeats excessively in a server render StyledComponent.ts already warns, in development, once a single styled component emits 1000+ inline style tags in one server render (a very large repeated list that should share one className instead). Per-instance emission means createGlobalStyle can hit the same excess, with no warning at all. Moves RSC_REDUNDANT_EMIT_WARN_THRESHOLD to src/constants.ts so both StyledComponent.ts and createGlobalStyle.ts share one constant, and adds the same dev-only, React.cache-scoped counter to createGlobalStyle's RSC emission branch, with IS_RSC leading the guard the same way StyledComponent.ts's does (so the browser build drops the whole expression; NODE_ENV first would leave a bare `process` reference, #5819). The message names the global style's id and suggests moving it higher in the tree so it mounts once, since createGlobalStyle has no attrs-style remediation to point at. Verified against the built output (pnpm build): the warning string is absent from both browser bundles and both native bundles, present in both server/RSC bundles. * test: check browser bundles for Node globals with an AST walk The regex-based checks required a punctuation character immediately before process/Buffer/global/__dirname/__filename/setImmediate, so `return process.versions` (preceded by a space) slipped through uncaught. A looser regex would trip on prose in a dev warning string instead. Verified the old regex's blind spot directly: it returns zero matches against `return process.versions`. Adds src/test/nodeGlobalScan.ts: parses a bundle with acorn (rollup 3.30.0, the version installed here, has no rollup/parseAst export; acorn is already resolvable as a transitive dependency, so nothing new was added to package.json) and walks the AST for free Identifier references to those six names. Allowed: the direct operand of typeof, and process as the object of a .env member access. A binding position (a function/class name, an imported name, a statement label) is never flagged; a same-named variable's later read still is, since this is a syntactic check, not a scope resolver, an accepted limitation given a bundler has no reason to name a variable exactly `process` or `Buffer`. Red/green, run directly against the helper: flags `return process.versions` and `;Buffer.from(x)`, passes `typeof process`, `process.env.NODE_ENV`, and a string literal containing the word "process". * build: declare acorn for the bundle Node-global scan * fix(native): drop an undefined forwardedAs instead of forwarding as: undefined Matches web, which already omits it. * fix(native): strip // comments inside function arguments except url() Only url(...) needs its contents shielded (protocol-relative and scheme URLs). A line comment inside calc() or rgba() arguments is now stripped the same way a block comment there already was.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Add this suggestion to a batch that can be applied as a single commit.This suggestion is invalid because no changes were made to the code.Suggestions cannot be applied while the pull request is closed.Suggestions cannot be applied while viewing a subset of changes.Only one suggestion per line can be applied in a batch.Add this suggestion to a batch that can be applied as a single commit.Applying suggestions on deleted lines is not supported.You must change the existing code in this line in order to create a valid suggestion.Outdated suggestions cannot be applied.This suggestion has been applied or marked resolved.Suggestions cannot be applied from pending reviews.Suggestions cannot be applied on multi-line comments.Suggestions cannot be applied while the pull request is queued to merge.Suggestion cannot be applied right now. Please check back later.
Prior to v6 this built a new object
propsForElementwith only the forwarded props. Since v6, it changed to mutatingcontextin place, see 0b8605aThe new approach keeps the props but sets them undefined. This makes React emit errors in dev and test. Delete them from the context instead.
Additionally check and delete any undefined values in context, for example if
.attrs()sets some to undefined, they should be removed at this point.