CSS-in-JS libraries, like styled-components, have become more popular in recent years. They encapsulate CSS down to the component level and allow you to use JavaScript to define reusable styles.

Using styled-components, you can maintain the component-driven architecture that React already reinforces. But the library has some downsides too.

How Styled Components Work

The styled-components CSS-in-JS library allows you to write CSS inside your component files. Its syntax is the same as CSS, so it's pretty easy to pick up. It's a perfect middle ground for JavaScript developers who tend to stay away from pure CSS.

To see how it works, consider the following Title component that renders an h1 element.

        const Title = styled.h1`
  font-size: 1.5em;
  text-align: center;
  color: red;
`;

You can use this component like any other React component.

        const Home = () => {
return (
<Title>A styled component heading</Title>
)
}

It's also very powerful because it makes it easier to work with props and state.

For instance, the color and background of this component depend on the props.

        import styled from "styled-components";
 
const Button = styled.button`
  padding: 0.8rem 1.6rem;
  background-color: ${(props) => (props.primary ? "purple" : "white")};
  border: 1px solid #00000;
  color: ${(props) => (props.primary ? "white" : "purple")};
`;
 
export default function Home() {
  return <Button primary>Primary</Button>
}

With styled components, you don't need to manually pass the props to the CSS. It is automatically available, simplifying writing styles that depend on data from the component.

Pros of Using Styled Components

Here are some advantages of using the styled-components library.

It Solves CSS Specificity Problems

Styled components eliminate specificity problems as it encapsulates CSS inside a component. This means you don't have to worry about class names clashing or your UI turning into a mess due to class name clashes.

Allows You to Write CSS Inside Components

As seen from the button component example, styled-components allows you to combine CSS and JS in the same file. So, you don't need to create a separate CSS file or keep switching from file to file.

This is a huge advantage when creating UI kits because you store all the functionality of the components in one file.

Other than that, writing CSS inside components. It makes it easier to share props and states with styles.

Allows Type Checking

With styled components, you can type-check the props and values used in your styles. For example, you can rewrite the button component above using TypeScript.

        interface props {
    primary: boolean
}

const Button = styled.button<props>`
  padding: 0.8rem 1.6rem;
  background-color: ${(props) => (props.primary ? "purple" : "white")};
  border: 1px solid #00000;
  color: ${(props) => (props.primary ? "white" : "purple")};
`;

Using TypeScript in the component means checking type errors as you code and reducing debugging time.

Supports Theming Out of the Box

Adding a dark theme or any other theme to your application can be difficult and time-consuming. However, Styled components simplify the process. You can add themes to your app by exporting a <ThemeProvider> wrapper component.

        const Button = styled.main`
  background-color: ${props => props.theme.light.background};
  color: ${props => props.theme.light.fontColor};
`

<ThemeProvider theme={theme}>
  <Button>
    Light button
  </Button>
</ThemeProvider>

The ThemeProvider component passes the themes to all the styled components it wraps. These components can then use the theme values in their styles. In this example, the button uses the theme values for the background and font colors.

Cons of Using Styled Components

While using the styled-components library has many benefits, it also has disadvantages.

It's Not Framework Independent

Writing CSS in JS means separating the two in the future will be difficult, which is terrible for maintainability. For example, if you ever decide to switch your JavaScript framework, you will need to rewrite most of your codebase.

This is time-consuming and costly. Using CSS modules or a framework independent library like emotion is more future-proof.

It Can Be Hard to Read

Differentiating between styled and React components can be difficult, especially outside of an atomic design system. Consider this example:

        <Main>
  <Nav>
    <ListItem>
      <LinkText>Adopt a Pet</LinkText>
    </ListItem>
    <ListItem>
      <LinkText>Donate</LinkText>
    </ListItem>
  </Nav>
  <Header>Adopt, don't shop!</Header>
  <SecondaryBtn btnText="Donate" />
</Main>

The only way of knowing which component contains business logic is by checking if it has props. Furthermore, even though the component names in this example are descriptive, it's still difficult to visualize them.

For example, the Header component might be a heading, but unless you check the styles, you may never know whether it's an h1, h2, or h3.

Some developers solve this problem by only using the styled component as a wrapper and using the semantic HTML tags for the elements inside it.

In this example, the header component could use an h1 tag.

        <h1>Adopt, don't shop!</h1>

You can take this further by defining the styled components in another file (e.g. styled.js), which you can later import into a React component.

        import * as Styled from './styled'

// use styled.components
<styled.Main>
// code
</styled.Main>

Doing this gives you a clear view of which components are styled and which are React components.

Styled Components Are Compiled at Runtime

For applications that use styled components, the browser downloads the CSS and parses it using JavaScript before injecting them into the page. This causes performance issues because the user must download a lot of JavaScript in the initial load.

Static CSS is much faster. It doesn't need to be processed before the browser uses it to style pages. However, the styled-components library is improving with every release. If you can afford some reduced performance, go ahead and use it.

When to Use Styled Components

Some developers enjoy writing CSS in JS files, while others prefer to have separate CSS files. How you choose to write CSS should ultimately depend on the project itself and what you or your team likes. Styled components are a good choice for building a UI library since everything can be in one file and easily be exported and reused.

If you prefer writing pure CSS, use CSS modules. You can have separate CSS files, and it locally scopes styles by default. Regardless of what choice you make, having solid CSS knowledge is essential.