In this blog post I am going to express my opinion and share my experience with the Styled components library.
I have tried all of the listed CSS approaches and my favorite is definitely Styled components. I had the opportunity to use it in a couple of production React application and here are my conclusions:
- Reusable – just as the normal React components, you can make small reusable pieces of code and avoid code duplication. Typical use cases are buttons, tables, forms, etc.
- Dynamic styling – By using props you can have dynamic values, which gives you a high level of flexibility by avoiding writing duplicated styles.
- Out-of-the-box theming support – with ThemeProvider you can create a powerful theme-based architecture while maintaining full control over the styling in the individual component.
- No class name bugs – Styles components generate unique class names for the defined styles. In this way, there is no duplication or unexpected overwriting.
- Better performance – The library is smart enough to keep track of the components rendered on a page and not load the styling for unused components. In big application, this may have a big impact on the performance in comparison to the “old school” styling where you load all the styles at once.
- React Native support – styled-components has great support for React Native apps as well. I recommend it to everyone who doesn’t like the default JS approach of styling React Native apps.
- Unusual approach – to be honest, initially, writing styles in this way seemed very odd to me. Nevertheless, after finishing a couple of features, I started to get comfortable with it and to enjoy it more
- Polluting the React DOM – well, opening the React Devtools extension in an app that makes use of Styled components can really surprise you. You may not realize it while coding, but the library adds many levels of nesting, and debugging can get tedious.
- Workarounds required – you can easily overengineer your app by creating a separated styled component for each DOM element. I discourage you to do so. In order to avoid this, you can nest rules inside your Styled component, but that can create conflicts and make your style definitions harder to debug. It’s always a matter of trade-offs.
If you are starting a new React project, I strongly encourage you to give it a try. Despite my objections, I believe Styled components is by far, the best way to handle styling in the React ecosystem, and its popularity keeps rising.