Skip to content

feat: use insertion effects when available - #4332

Closed
stipsan wants to merge 1 commit into
styled-components:mainfrom
sanity-io:main
Closed

stipsan wants to merge 1 commit into
styled-components:mainfrom
sanity-io:main

Conversation

@stipsan

@stipsan stipsan commented Jul 12, 2024 •

Copy link
Copy Markdown

At sanity we use styled-components extensively, our @sanity/ui design system is built upon it, and most of the Sanity Studio codebase is as well. We've been testing the impact of implementing useInsertionEffect and see a noticeable performance improvement both on component mounting and rerender perf when the CSS is changed and it motivated us to open a PR 🙌

The new React docs explains useInsertionEffect really well, especially the section at the end:

How is this better than injecting styles during rendering or useLayoutEffect?
If you insert styles during rendering and React is processing a non-blocking update, the browser will recalculate the styles every single frame while rendering a component tree, which can be extremely slow. useInsertionEffect is better than inserting styles during useLayoutEffect or useEffect because it ensures that by the time other Effects run in your components, the < style > tags have already been inserted. Otherwise, layout calculations in regular Effects would be wrong due to outdated styles.

Using Insertion Effects in StyledComponent

The work in this implementation builds upon @alexandernanberg's work in #3821 and how Emotion implements it.
By using useInsertionEffectAlwaysWithSyncFallback from @emotion/use-insertion-effect-with-fallbacks we are able to:

  • React 18 and later the useInsertionEffect hook is used to write to the CSSOM.
  • React 17 and older will continue to emit during render, ensuring the CSSOM is updated before userland useEffect and useLayoutEffect hooks are called.

Using Insertion Effects in createGlobalStyle

I'm using useInsertionEffectWithLayoutFallback from @emotion/use-insertion-effect-with-fallbacks to ensure that Insertion Effects are used while available, otherwise Layout Effects are used like it is now.

I saw that global styles used to opt-in to Insertion Effects in the past, but it was reverted in #4101.
It seems like the React team doesn't see the behaviour as a bug, and there's ways to make global styles mounted in a suspended component (like in a React.lazy) eagerly run teardown and remove global styles:

  • use a startTransition to wrap events that lead to React.lazy, or general suspense
  • change the key of the parent Suspense boundary when you load a different React.lazy or suspending component
  • if changing the suspense key isn't viable then separate suspense boundaries could be used.

I forked @mdeschamps codesandbox and modified it to demonstrate how using a key prop on the outer Suspense boundary solves it (using our speedy-styled-components fork that implements this PR), it also has commented out code that uses startTransition instead of changing the key.

Testing

To run the benchmark, and tests, I've bumped react from 17 to 18. One doesn't simply bump test dependencies 😮‍💨 I changed it back to 17.
There's also a forked version of styled-components on npm that you can use to test the changes in this PR in userland: "styled-components": "npm:[email protected]".

@quantizor quantizor self-assigned this Jul 16, 2024
@stipsan
stipsan force-pushed the main branch 2 times, most recently from afef127 to 1481454 Compare July 16, 2024 20:52
@quantizor

quantizor commented Jul 17, 2024 •

Copy link
Copy Markdown
Contributor

Ran the benchmark suite (packages/benchmarks yarn build && open index.html)

Screenshot 2024-07-17 at 10 59 51 AM

Seems like there's an unfortunate performance degradation compared to current main branch for 2/3 usage scenarios

@stipsan

stipsan commented Jul 17, 2024

Copy link
Copy Markdown
Author

@quantizor this is for React 17 which should still be updating styles in render, right?
I'll try a few things and see what's causing it 🤔

@stipsan
stipsan force-pushed the main branch 3 times, most recently from 27403f5 to f2ef743 Compare July 17, 2024 23:51
@stipsan

stipsan commented Jul 18, 2024

Copy link
Copy Markdown
Author

@quantizor I've updated the implementation so it no longer has a perf regress:

image

The benchmark is pushed to a different branch, and pits the latest v6 release on npm, with an npm published version of the changes in this branch (currently: [email protected]): https://github.com/sanity-io/styled-components/tree/benchmark

When running the workspace version against v6 I get strange numbers, I tried to run a baseline (branch with repro), but for some reason the workspace version always gave worse numbers than the v6 published to npm:
Capture-2024-07-18-011014

@quantizor

Copy link
Copy Markdown
Contributor

Ok I found a discrepancy in the benchmark code that I fixed in main and we can properly test this now

@stipsan
stipsan force-pushed the main branch 4 times, most recently from 5d8c004 to fd88d40 Compare July 19, 2024 10:09
@stipsan

stipsan commented Jul 19, 2024

Copy link
Copy Markdown
Author

Thanks @quantizor, I merged in your changes and re-run the benchmarks. I ran each separately, multiple times so I could compare the median times and variance for each. As the benchmark is on react 17 we should see no difference since the logic for useInsertionEffect, that requires looping over the rules twice, shouldn't be used there:

  1. To gather them up during render.
  2. Insert them into the styleSheet in a useInsertionEffect cycle.

Mount deep

image
The workspace version is slightly faster with a median of 03.13 ms compared to v6's 03.18 ms. The average variances are identical (00.67 ms), indicating similar stability in performance.

Mount wide

image
The workspace version is slightly faster (04.14 ms vs. 04.16 ms) with a slightly lower variance (±00.28 ms vs. ±00.31 ms).

Update dynamic styles

image

The workspace version is faster (01.63 ms vs. 01.81 ms) with lower variance (±00.93 ms vs. ±01.06 ms).

Conclusion

The workspace version is overall faster and more stable compared to v6 in the benchmarks provided. Which is a bit surprising to me as I don't think it's actually faster. But it's probably fine as the goal in any case was to make sure it didn't regress 🤷

@stipsan

stipsan commented Jul 19, 2024

Copy link
Copy Markdown
Author

@quantizor I altered the benchmark to use react 18, and ReactDOM.createRoot from react-dom/client instead of ReactDOM.render, to opt-in to concurrent rendering features, and got these results:

image

The workspace version is consistently faster, though the differences are very small, and variance is generally comparable.

@stipsan

stipsan commented Aug 28, 2024

Copy link
Copy Markdown
Author

@quantizor I've made a repro that demonstrates the perf impact:

concurrent-styled-components.mov

Before / After

@quantizor

Copy link
Copy Markdown
Contributor

@quantizor I've made a repro that demonstrates the perf impact:

concurrent-styled-components.mov
Before / After

Thank you for making this! I really appreciate your effort and persistence here and will be happy to accept the enhancement 🚀


const isBrowser = typeof document !== 'undefined';
// @ts-expect-error - this is fine
const useInsertionEffect = React['useInsertion' + 'Effect']

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

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

What's going on here?

Copy link
Copy Markdown
Author

Choose a reason for hiding this comment

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

Emotion started using this pattern in emotion-js/emotion#2651, in response to community reports that some bundlers got build errors when versions older than React 18 were used: emotion-js/emotion#2649 🤔

@quantizor

Copy link
Copy Markdown
Contributor

Out of curiosity, what type of computer are you using to run this test? I'm on an M2 Macbook Air and these were my results

Baseline current proposed
Screenshot 2024-08-29 at 9 42 09 PM Screenshot 2024-08-29 at 9 37 31 PM Screenshot 2024-08-29 at 9 38 59 PM)

If anything it seems to perform slightly worse? This is with the force rerender flag turned on.

@stipsan

stipsan commented Aug 30, 2024

Copy link
Copy Markdown
Author

Out of curiosity, what type of computer are you using to run this test? I'm on an M2 Macbook Air and these were my results

Baseline current proposed
Screenshot 2024-08-29 at 9 42 09 PM Screenshot 2024-08-29 at 9 37 31 PM Screenshot 2024-08-29 at 9 38 59 PM)
If anything it seems to perform slightly worse? This is with the force rerender flag turned on.

The original implementation was focused on racing who can render the most iterations (1 iteration is when all cells have finished animating their background color) in total, even if it's at the cost of fps.

I've updated the benchmark to be more balanced, and configurable. It's still better to render the most iterations, but without sacrificing a stable, high, framerate.

In this video (before, after) I'm running two chrome (v128) windows in split screen on a M1 Pro at a 3456x2234 resolution, connected to a charger so there's no CPU throttling, running on macOS 14.5:

updated.bench.4K.mov

As you can see it reaches the 20th iteration twice as fast, while maintaining a stable FPS ranging 35-102 compared to 28-87 when useInsertionEffect isn't used 🙌

@changeset-bot

changeset-bot Bot commented Aug 30, 2024 •

Copy link
Copy Markdown

🦋 Changeset detected

Latest commit: ad94c91

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 Minor

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

@stipsan

stipsan commented Aug 30, 2024

Copy link
Copy Markdown
Author

Quick protip @quantizor, if you want to inspect in more detail what's happening, and what the React timeline looks like when the insert CSS during render version is tipping over and is taking too long to render, and you see the large chunks of tiles flashing, vs the insert CSS with useInsertionEffect is still able to finish in time, then you can add &maxIterations=3 to the URL so it's easier to use the React profiler.

I'm building the benchmark with next build --profile so you can use the React Devtools and its profiler on the deploy: https://concurrent-styled-components.sanity.dev

@stipsan

stipsan commented Nov 12, 2024

Copy link
Copy Markdown
Author

Hey @quantizor, anything I can do to help land this? 😄

@skovhus

skovhus commented Aug 11, 2025

Copy link
Copy Markdown

@stipsan so sorry to see this hanging here. We could really use some optimizations of styled components… curious if you forked styled components are patched it for your use case at Santiy.

@kmelve

kmelve commented Aug 29, 2025

Copy link
Copy Markdown

@skovhus and others who land here: We have open-sourced our fork that fixes a lot of these things. It's a stop gap for us as we're migrating out of SC/css-in-js, so it won't be actively maintained, but might be useful you're on the same journey: https://github.com/sanity-io/styled-components-last-resort

@quantizor

Copy link
Copy Markdown
Contributor

Happy to take a second look at this PR with some additional profiling data per https://x.com/quantizor/status/1966183924985442547?s=46

@stipsan

stipsan commented Sep 11, 2025

Copy link
Copy Markdown
Author

Happy to take a second look at this PR with some additional profiling data per https://x.com/quantizor/status/1966183924985442547?s=46

Did you see #4332 (comment)?
It's not expected that using useInsertionEffect is significantly (if at all) faster than inserting CSS during render in ideal scenarios. useInsertionEffect is still before useLayoutEffect and useEffect, like the render approach.
The difference happens when you are in concurrent scenarios:

  • Suspending during render (React.lazy or React.use or promises thrown don't matter), view unmounts before it resolves (no CSS should be inserted, the component was never in the DOM and never will).
  • Stale content indicators that are skipped since the transition finishes fast enough:
    import { Suspense, useState, useDeferredValue } from 'react';
    import { styled } from 'styled-components';
    import SearchResults from './SearchResults.js';
    
    const Wrapper = styled.div<{$isStale: boolean}>`
      opacity: ${({$isStale}) => $isStale ? 0.5 : 1};
      transition: ${({$isStale}) => $isStale ? 'opacity 0.2s 0.2s linear' : 'opacity 0s 0s linear'};
    `
    
    export default function App() {
      const [query, setQuery] = useState('');
      const deferredQuery = useDeferredValue(query);
      const isStale = query !== deferredQuery;
      return (
        <>
          <label>
            Search albums:
            <input value={query} onChange={e => setQuery(e.target.value)} />
          </label>
          <Suspense fallback={<h2>Loading...</h2>}>
            <Wrapper $isStale={isStale}>
              <SearchResults query={deferredQuery} />
            </Wrapper>
          </Suspense>
        </>
      );
    }
    In this case, if <SearchResults> don't suspend because the query is already cached it's unnecessary for CSS rules to be inserted for the $isStale={true} state, using useInsertionEffect gives us the chance to skip it.

There are many others, but the TL;DR is that the current benchmarks on this repo isn't equipped to test them.

@lucaswitch

Copy link
Copy Markdown
Contributor

I really love everything styled-components stands for. There is no easier way to write styles in react-native. Is it possible to have that PR on some kind o minor version?

@lucaswitch

Copy link
Copy Markdown
Contributor

I really love everything styled-components stands for. There is no easier way to write styles in react-native. Is it possible to have that PR on some kind o minor version?

Not related with this PR itself but i think the most performant way to write styles for react-native is using the built in StyleSheet.create() method. Do https://github.com/styled-components/babel-plugin-styled-components already do that?

@stipsan

stipsan commented Jan 15, 2026

Copy link
Copy Markdown
Author

Based on @quantizor's lack of response in this thread, as well as on #5607 (comment), combined with the recent work creating lots of merge conflicts with the release of 6.3 with RSC support, I'm closing this PR.

Instead of declining the PR, or giving any actionable feedback so the PR can be moved forward and land, @quantizor have chosen to simply ghost it. It took an incredible amount of effort and time for me to work on this, and I've respected @quantizor's time and been patiently waiting.
It's sad that in the end it feels like a wasted effort, and seeing activity on main feels insulting rather than encouraging.

@stipsan stipsan closed this Jan 15, 2026
@quantizor

Copy link
Copy Markdown
Contributor

Actually I've replied multiple times in different places. On twitter and I also spent a decent amount of time in #5607 on it. The reason why this hasn't moved forward is I simply have not been able to find proof yet outside of Sanity that it provides a clear benefit.

@skovhus

skovhus commented Jan 15, 2026

Copy link
Copy Markdown

👋🏼 Using the insertion effect was a huge improvement for us at Linear, as described here: https://www.sanity.io/blog/cut-styled-components-into-pieces-this-is-our-last-resort

@quantizor

Copy link
Copy Markdown
Contributor

Alright, I'll come back to this. Trying to get the new RSC workaround put to bed without a new major. The React 19-specific improvements to drop ServerStyleSheet look interesting, but that's definitely a breaking change so it would need to come after.

Honestly my current struggle is just getting enough timely testing and good bug reports. We're getting there.

@quantizor

Copy link
Copy Markdown
Contributor

On another note, it seems like you both are very passionate about this and, perhaps more importantly, have useful production setups to actually test meaningful improvements. I'd be open to inviting either or both of you as co-maintainers if that interests you.

At this point, I'm just trying to do my best but am kind of flying blind in various ways.

@stipsan

stipsan commented Jan 15, 2026

Copy link
Copy Markdown
Author

Actually I've replied multiple times in different places. On twitter and I also spent a decent amount of time in #5607 on it. The reason why this hasn't moved forward is I simply have not been able to find proof yet outside of Sanity that it provides a clear benefit.

You never got back to me on #4332 (comment), I don't know if you've seen it, if you've seen it I don't know why you're unconvinced it has a clear benefit, it would be nice if I could get feedback on that.
I feel like the benefit was pretty clear, and if you disagree it would be useful to get any actionable feedback so I know what type of data you're after.
Just to reiterate, the purpose of useInsertionEffect is not to be strictly faster than inserting CSS rules during render. It is to provide the same timing as inserting during render, without the downsides of bad case scenarios (the whole purpose of https://concurrent-styled-components.sanity.dev/?layoutTrashing=force is to demonstrate an extreme version of such a worst case scenario).
The guidance by the react core team on useInsertionEffect is really clear, CSS-in-JS libraries are supposed to use it, and other libraries like emotion and styled-jsx are already using the hook. If you think that guidance shouldn't be followed, or somehow doesn't apply to styled-components, then I feel the burden of proof is on you to demonstrate why it shouldn't be adopted.

Alright, I'll come back to this. Trying to get the new RSC workaround put to bed without a new major. The React 19-specific improvements to drop ServerStyleSheet look interesting, but that's definitely a breaking change so it would need to come after.

On RSC, based on our experience targeting it, the best approach is to use "react-server" export conditions. All React RSC frameworks implements that protocol (it's how server-only and client-only is implemented) and it helps avoiding bloat in the browser bundle, and it's the official way, typeof React.createContext is clever but it feels like shaky ground since it's not how RSC libraries are intended to be shipped 😅 .

On another note, it seems like you both are very passionate about this and, perhaps more importantly, have useful production setups to actually test meaningful improvements. I'd be open to inviting either or both of you as co-maintainers if that interests you.

At this point, I'm just trying to do my best but am kind of flying blind in various ways.

Look, I know how hard it is to be a solo maintainer so I'm happy to come on as a co-maintainer and help. Creating the sc forks (@sanity/styled-components and @sanity/css-in-js) were a last resort, it's not good for the ecosystem to have fragmentation like this. And I truly believe that if a project is going to use a runtime CSS-in-JS solution then SC is the most performant and best way to do it so I think there's value in maintaining it and keeping it up to date with the latest capabilities of react.

I have low availability/bandwidth until March, I'd be happy to come onboard then and start working on contributing back upstream the improvements we've done in our forks 🙌

@quantizor

Copy link
Copy Markdown
Contributor

Get in touch when you free up, I'd be happy to welcome you and the community would benefit from your involvement. 😃

@quantizor

quantizor commented Apr 4, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for this PR and the detailed write-up — it directly informed the performance work in the upcoming 6.4 release.

We implemented the useInsertionEffect buffering pattern (Emotion-style syncFallback, ref-backed buffer for Strict Mode compat, per-componentId tracking for inheritance chains) and tested it extensively in a new sandbox with stress-test scenarios. The implementation was correct, but in empirical benchmarking the 6.4 render cache + synchronous injection path was consistently faster than the useInsertionEffect variant. The buffer allocation, ref overhead, and deferred flush add per-render cost that outweighs the savings from avoiding wasted CSSOM writes during concurrent interruptions — at least for the workloads we tested.

The implementation is preserved for future evaluation, particularly if Suspense-heavy patterns become more common and the concurrent interruption cost becomes dominant.

In the meantime, 6.4 includes substantial performance improvements that should address the original motivation:

  • Parent re-render: 3.3x faster (render cache skips style resolution entirely on cache hit)
  • First mount: 1.7–2.5x faster
  • Prop cycling: 2.3–2.4x faster

Plus first-class RSC support, createTheme for CSS variable theming, and many other improvements.

Would love for you to try the prerelease and share your benchmarks:

npm i styled-components@test

Release PR: #5687

@stipsan

stipsan commented Apr 10, 2026

Copy link
Copy Markdown
Author

Get in touch when you free up, I'd be happy to welcome you and the community would benefit from your involvement. 😃

I'm back, I'd love to get involved, reach out on [email protected] and let's have a chat 🙌

Thanks for this PR and the detailed write-up — it directly informed the performance work in the upcoming 6.4 release.

We implemented the useInsertionEffect buffering pattern (Emotion-style syncFallback, ref-backed buffer for Strict Mode compat, per-componentId tracking for inheritance chains) and tested it extensively in a new sandbox with stress-test scenarios. The implementation was correct, but in empirical benchmarking the 6.4 render cache + synchronous injection path was consistently faster than the useInsertionEffect variant. The buffer allocation, ref overhead, and deferred flush add per-render cost that outweighs the savings from avoiding wasted CSSOM writes during concurrent interruptions — at least for the workloads we tested.

The implementation is preserved for future evaluation, particularly if Suspense-heavy patterns become more common and the concurrent interruption cost becomes dominant.

In the meantime, 6.4 includes substantial performance improvements that should address the original motivation:

  • Parent re-render: 3.3x faster (render cache skips style resolution entirely on cache hit)
  • First mount: 1.7–2.5x faster
  • Prop cycling: 2.3–2.4x faster

Plus first-class RSC support, createTheme for CSS variable theming, and many other improvements.

Would love for you to try the prerelease and share your benchmarks:

npm i styled-components@test

Release PR: #5687

Really impressive improvements! I'll find time next week and run some benchmarks and report back 👍
Just wanted to callout that "Suspense-heavy" patterns includes concurrent features that are in play when using other features that are part of "Async React", like <Activity mode="hidden">, useOptimistic, startTransition, and those will pick up in prevalence significantly as the Async Working group has it as their mission to now spread docs and knowledge on how to best use these patterns, now that they were complete in React 19.2. Highly recommend watching Ricky's talk.
Maybe we could allow choosing which implementation to use at runtime, either by env flag, withConfig({useInsertionEffect: true}), or both, similar to how SC_SPEEDY is configurable atm.

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.

5 participants