DEV Community

Discussion on: Styled Web Components

Collapse
 
ashubham profile image
Ashish Shubham

This creates copies of your styles in each instance of the component. Hence not reccommended

Collapse
 
alfredosalzillo profile image
Alfredo Salzillo • Edited

This is not true.

Styles are not injected inside a <style></style>, nor in the style attribute, but are injected inside a shared instance of CSSStyleSheet adopted by the shadow root (if using it) and the outer root (light or shadow) of the element.

Every time the style is recalculated, the style for the unique class name, calculate using only the CSS text of the parsed style, is injected in the CSSStyleSheet if not present.

As a plus, not only instances of the same component, share the same set of class names, but also different element with equals parsed CSS string.

For example:

styled.div`
  background-color: black;
`
styled.span`
  background-color: black;
`
styled.button`
  background-color: black;
`

The instances of the three styled-components share the same class name.

Collapse
 
ashubham profile image
Ashish Shubham

Well, if the instances share the same styles, how are you able to reactively change the styles based on props ? The styles for all instances would change based on props passed to a single instance ?

Thread Thread
 
alfredosalzillo profile image
Alfredo Salzillo

An unique class name, based on the style, is created and added to the element every time props changes. The old class name if present is removed.
Take a look at the code.