Skip to content

fix: resolve createGlobalStyle SSR issue in v6.3.x - #5638

Merged
quantizor merged 13 commits into
mainfrom
copilot/fix-global-styles-issue
Jan 16, 2026
Merged

quantizor merged 13 commits into
mainfrom
copilot/fix-global-styles-issue

Conversation

Copilot AI commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor

Fix createGlobalStyle compatibility with React StrictMode

  • Investigate the issue with createGlobalStyle in React StrictMode
  • Identify root cause: cleanup runs after StrictMode's simulated remount
  • Implement fix:
    • Static styles only inject once (skip if already exists)
    • Use queueMicrotask for StrictMode-aware cleanup
    • Use React.useRef for per-instance state tracking
  • Add comprehensive StrictMode tests
  • Update existing tests for async cleanup behavior
  • Run all tests (406 pass)
  • Code review (addressed race condition feedback)
  • Security scan (no alerts)
  • Simplified cleanupRef to use boolean instead of object wrapper

Problem

In React StrictMode, components are unmounted and remounted to help identify side effects. The previous implementation had issues:

  1. Static styles: Were removed and re-added on every render, causing flickering
  2. StrictMode cleanup: The cleanup effect from the simulated unmount would run after the remount, removing styles that should persist

Solution

  1. Static styles optimization: Only inject once if not already present
  2. StrictMode-aware cleanup: Use queueMicrotask to delay cleanup. In StrictMode's remount, the next effect runs before the microtask, canceling the cleanup. In real unmount, no new effect runs, so styles are removed.
  3. Per-instance state: Use React.useRef<boolean> to track cleanup state per component instance

Related Issues

Original prompt

This section details on the original issue you should resolve

<issue_title>Changed behavior for createGlobalStyle in v6.3.x</issue_title>
<issue_description>Updating to v6.3.0 did break my global styles. I also see the following warning:

Warning: useLayoutEffect does nothing on the server, because its effect cannot be encoded into the server renderer's output format. This will lead to a mismatch between the initial, non-hydrated UI and the intended UI. To avoid this, useLayoutEffect should only be used in components that render exclusively on the client. See https://reactjs.org/link/uselayouteffect-ssr for common fixes.
    at u (/Users/koenpunt/Developer/koenpunt/kakhiel-web-secondary/node_modules/styled-components/src/constructors/createGlobalStyle.ts:32:17)

I think the culprit is here, because I do see a flash of the expected styles, but then those styles are removed.

if (!IS_RSC && typeof React.useLayoutEffect === 'function') {
React.useLayoutEffect(() => {
return () => {
globalStyle.removeStyles(instance, ssc.styleSheet);
};
}, [instance, ssc.styleSheet]);
}

Before the condition was if (!__SERVER__) {, and I think that using the presence of React.useLayoutEffect isn't a reliable check for whether the code is running in a client environment.

I'm using React 18.3.1.</issue_description>

<agent_instructions>Thoroughly investigate this issue again, focusing on the changes to createGlobalStyle since 6.3.x. Determine what changed that could lead to inconsistent injection. Consider both RSC and non-RSC scenarios, including the new style hoisting behavior (does this break React 18 usage subtly?)</agent_instructions>

Comments on the Issue (you are @copilot in this section)

@quantizor Thanks, on it! @quantizor Thank you for reporting, if there's any additional information you could provide it would be helpful. Even better if someone is able to put together a minimal reproduction? There's a sandbox subproject in this repo that can be used/manipulated to show the problem.

✨ Let Copilot coding agent set things up for you — coding agent works faster and does higher quality work when set up for your repo.


Note

Ensures createGlobalStyle behaves correctly in StrictMode, concurrent rendering, and RSC, while cleaning up SSR hoisted tags and tightening RSC guards.

  • Static global styles inject once; dynamic styles avoid flicker via StrictMode-aware cleanup using useRef + queueMicrotask
  • On unmount/rerender, removes accumulated SSR inline style[data-styled-global] tags via new removeGlobalStyleTag
  • RSC: unify !IS_RSC ? React.useContext(...) usage across core (createGlobalStyle, withTheme, StyledComponent, ThemeProvider, StyleSheetManager); emit stable href for RSC style tags (supports HMR) with new RSC tests
  • Add/adjust tests for StrictMode persistence, unmount/remount cleanup, and async microtask timing
  • package.json: add optional @types/react and @types/react-dom to peer deps
  • Restore styled.br in supported DOM elements

Written by Cursor Bugbot for commit d398d63. This will update automatically on new commits. Configure here.

@changeset-bot

changeset-bot Bot commented Jan 13, 2026 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: d398d63

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 changed the title [WIP] Fix global styles behavior with createGlobalStyle in v6.3.x Investigate createGlobalStyle SSR issue in v6.3.x Jan 13, 2026
Copilot AI requested a review from quantizor January 13, 2026 14:28
@quantizor

Copy link
Copy Markdown
Contributor

@copilot See this comment specifically, we're missing something #5632 (comment)

Copilot AI commented Jan 13, 2026 •

Copy link
Copy Markdown
Contributor Author

@copilot See this comment specifically, we're missing something #5632 (comment)

Found the issue. The GlobalStyle.renderStyles() method was removing and re-creating styles on every render, causing a brief moment where styles don't exist. This could cause visual glitches with React 18/19 concurrent rendering and interfere with React 19's style hoisting behavior.

Fixed in commit 21a1db7f by adding an optimization for static global styles: if the styles already exist in the stylesheet, skip the remove/re-create cycle. This mirrors the optimization in ComponentStyle.generateAndInjectStyles() which also checks hasNameForId before inserting.

Warning

Firewall rules blocked me from connecting to one or more addresses (expand for details)

I tried to connect to the following addresses, but was blocked by firewall rules:

  • nextjs.org
    • Triggering command: /home/REDACTED/work/_temp/ghcca-node/node/bin/node /home/REDACTED/work/_temp/ghcca-node/node/bin/node --enable-source-maps /home/REDACTED/work/_temp/copilot-developer-action-main/dist/index.js (dns block)

If you need me to access, download, or install something from one of these locations, you can either:

@quantizor

Copy link
Copy Markdown
Contributor

@copilot Ok, we have a few more things to look into: #5641

Copilot AI commented Jan 13, 2026

Copy link
Copy Markdown
Contributor Author

@copilot Ok, we have a few more things to look into: #5641

Investigated both issues and the React StrictMode behavior.

Issue #5641 (HMR styles not removed): This is a separate issue related to React 19's style hoisting with the precedence attribute in RSC mode. When styles change during HMR, React adds new <style> tags but doesn't remove old ones. This needs a different solution (potentially tracking and cleaning up old href values).

React StrictMode fix (commit e388c07):

  • Static styles now only inject once (skip if already exists)
  • Use queueMicrotask for StrictMode-aware cleanup - in StrictMode's simulated remount, the next effect cancels the cleanup; in real unmount, styles are properly removed
  • Use React.useRef for per-instance cleanup state tracking

Added comprehensive tests for StrictMode double-render behavior. All 406 tests pass.

Copilot AI and others added 5 commits January 13, 2026 16:09
Static global styles are now only injected once and skipped on re-renders,
preventing issues with React 18/19 concurrent rendering where the brief
removal and re-addition of styles could cause visual glitches or interfere
with React 19's style hoisting behavior.

Co-authored-by: quantizor <[email protected]>
- Static styles now only inject once (skip if already exists)
- Use queueMicrotask for StrictMode-aware cleanup coordination
- Use React.useRef for per-instance cleanup state tracking
- Updated tests to handle async cleanup with await Promise.resolve()

Co-authored-by: quantizor <[email protected]>
Changed from `useRef<{ shouldRemove: boolean }>` to `useRef<boolean>` since
the ref object itself is stable and there's no need for the extra wrapper.

Co-authored-by: quantizor <[email protected]>
@quantizor
quantizor force-pushed the copilot/fix-global-styles-issue branch from 7df0a47 to 1540944 Compare January 13, 2026 21:23
@quantizor
quantizor marked this pull request as ready for review January 13, 2026 21:23
@quantizor quantizor changed the title Investigate createGlobalStyle SSR issue in v6.3.x fix: resolve createGlobalStyle SSR issue in v6.3.x Jan 16, 2026
When a server-defined createGlobalStyle is conditionally rendered in a client component, React 19's hoisted style tags with precedence attribute would persist in the DOM even after the component unmounts. This caused accumulated style tags and incorrect CSS.

The fix adds removeGlobalStyleTag() to sheet/dom.ts which removes all SSR-rendered inline style tags (data-styled-global) when the GlobalStyle cleanup effect runs on the client.
@quantizor
quantizor force-pushed the copilot/fix-global-styles-issue branch from 8a6d1d1 to 1a33199 Compare January 16, 2026 04:41
@quantizor
quantizor merged commit 51ffa9c into main Jan 16, 2026
@quantizor
quantizor deleted the copilot/fix-global-styles-issue branch January 16, 2026 04:53

@cursor cursor Bot 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.

Cursor Bugbot has reviewed your changes and found 3 potential issues.

Bugbot Autofix is OFF. To automatically fix reported issues with Cloud Agents, enable Autofix in the Cursor dashboard.

This is the final PR Bugbot will review for you during this billing cycle

Your free Bugbot reviews will reset on February 7

Details

You are on the Bugbot Free tier. On this plan, Bugbot will review limited PRs each billing cycle.

To receive Bugbot reviews on all of your PRs, visit the Cursor dashboard to activate Pro and start your 14-day free trial.

// These persist in the DOM because React 19's hoisted styles don't unmount
removeGlobalStyleTag(styledComponentId);
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Race condition: stale ref allows microtask to remove active styles

High Severity

The shouldRemoveRef is created per React component instance, but the instance number is shared via the instanceMap WeakMap across all React instances of the same GlobalStyle. When a component unmounts and a new instance immediately remounts (before the microtask runs), the new instance creates a fresh ref (refB) while the scheduled microtask still holds a closure over the old ref (refA). Since refA.current remains true, the microtask proceeds to remove styles that the newly-mounted instance needs. For static styles, the check hasNameForId(id, id) returns true during the new render so styles aren't re-injected, leaving the component without styles.

Fix in Cursor Fix in Web

// These persist in the DOM because React 19's hoisted styles don't unmount
removeGlobalStyleTag(styledComponentId);
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Concurrent GlobalStyle instances: one unmount removes styles for all

Medium Severity

When multiple React component instances of the same GlobalStyle are mounted simultaneously (e.g., <><GlobalStyle /><GlobalStyle /></>), unmounting one instance removes styles for all. Each instance creates its own shouldRemoveRef, but they share the same instance number from the instanceMap WeakMap. When Instance A unmounts, its cleanup checks refA.current (which is true) and removes styles for the shared instance. Instance B's ref being false doesn't prevent this since the microtask captured Instance A's ref, not Instance B's.

Fix in Cursor Fix in Web

// These persist in the DOM because React 19's hoisted styles don't unmount
removeGlobalStyleTag(styledComponentId);
}
});

Copy link
Copy Markdown

Choose a reason for hiding this comment

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

Missing style cleanup when StyleSheet dependencies change causes leak

Low Severity

When the effect's dependencies (instance or ssc.styleSheet) change, the old styles are never cleaned up. The cleanup function schedules a microtask with shouldRemoveRef.current = true, but the new effect immediately runs and sets shouldRemoveRef.current = false before the microtask executes. The microtask then skips cleanup because the ref is false. The previous synchronous cleanup directly called globalStyle.removeStyles() and properly removed old styles. This causes styles to leak in the old StyleSheet when StyleSheetManager's target or sheet prop changes dynamically.

Fix in Cursor Fix in Web

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.

Changed behavior for createGlobalStyle in v6.3.x

2 participants