emotion-js/emotion

classNames added to inline styles multiple times resulting in duplicate CSS

Closed this issue · 3 comments

Current behavior:
I'm currently seeing duplicate style tags added in my app. Each time I use an emotion styled component more than once it adds the same style to the inline styles of my application. At first I thought it was caused by hot reloading but I'm seeing the same thing in production builds as well

I end up with the following:

Screen Shot 2021-07-19 at 1 37 13 PM

To reproduce:
https://codesandbox.io/s/affectionate-mcnulty-dsnwj?file=/pages/index.js

  1. Create a styled component with emotion
  2. Add it to the page 2 or more times.
  3. Inspect the element to see multiple style declarations and/or search the source to see the className is applied more than once to the inline styles

Expected behavior:
Duplicate use of components should not result in duplicate CSS

Environment information:

"devDependencies": {
  "@emotion/babel-plugin": "11.0.0"
},
"dependencies": {
  "@emotion/react": "11.4.0",
  "@emotion/styled": "11.3.0",
  "next": "latest",
  "react": "^17.0.2",
  "react-dom": "^17.0.2"
}

I'm running into the same issue in a Create React App setup with the @emotion/css package.

@jbsmith731 sorry for the long reply. The issue is most likely that those elements don't have a common Emotion-aware ancestor. You can fix this by wrapping the whole thing with a CacheProvider or some dummy <div css={{position: 'initial'}}><App/></div>

@CoryDuncan The issue reported by @jbsmith731 is related to SSR - CRA doesn't support that (also his issue is about @emotion/react and not @emotion/css. Please open a new issue with the issue reproduction so I could take a look.

same issue. doesn't work.

tried this <div css={{position: 'initial'}}>
didn't work.