Support renderToPipeableStream and eliminate the need for EmotionCache in React 19Β #3283
Description
The problem
To avoid putting style tags next to a component one has to use EmotionCache, extract the CSS, and follow a somewhat cumbersome server setup for SSR. This setup also does not appear to support renderToPipeableStream.
Proposed solution
In React 19 style tags can be hoisted to the head if you add an href and precedence to your style tags. Adding these attributes to style tags inserted by Emotion eliminates the need to use EmotionCache.
See: https://react.dev/reference/react-dom/components/style#special-rendering-behavior
I see no real drawbacks. On might need to detect the React version to avoid unnecessary attributes on older versions of React.
Alternative solutions
It seems a lot more complicated to support renderToPipeableStream with EmotionCache as can be seen by the issues that have been open for years.
Additional context
I've forked @emotion/styled into my project and simply replaced:
<style
{...{
[`data-emotion`]: `${cache.key} ${serializedNames}`,
dangerouslySetInnerHTML: { __html: rules },
nonce: cache.sheet.nonce,
}}
/>
with
<style
{...{
[`data-emotion`]: `${cache.key} ${serializedNames}`,
dangerouslySetInnerHTML: { __html: rules },
nonce: cache.sheet.nonce,
href: serializedNames,
precedence: 'lower'
}}
/>
and it worked flawlessly.