styled-components brings a new approach to styling React components — CSS directly in JavaScript with the full power of the language. No more CSS class name collisions.
Problems with traditional CSS in a component world¶
CSS was designed for documents, not components. In a React application with dozens of components you run into:
- Global scope — class names collide across components
- Dead code — you do not know which styles are still in use
- Dynamic styles — CSS has no access to props and state
- Co-location — styles are separate from the components they style
styled-components solves all these problems.
Tagged template literals¶
styled-components uses ES6 tagged template literals:
import styled from 'styled-components';
const Button = styled.button`
background: ${props => props.primary ? '#00d4ff' : 'transparent'};
color: ${props => props.primary ? '#040c0f' : '#00d4ff'};
font-size: 1rem;
padding: 0.5rem 1.5rem;
border: 2px solid #00d4ff;
border-radius: 4px;
cursor: pointer;
&:hover {
background: #00d4ff;
color: #040c0f;
}
`;
// Usage
<Button primary>Primary action</Button>
<Button>Secondary</Button>
Each component generates a unique class name — no collisions, no BEM, no overhead.
Advantages of CSS-in-JS¶
Why CSS-in-JS makes sense:
- Scoping — automatically isolated styles per component
- Dynamic styles — full access to props and state
- Dead code elimination — delete the component and the styles disappear with it
- Theming — ThemeProvider for consistent design tokens
- Server-side rendering — critical CSS extraction automatically
- TypeScript support — typed props for styles
Criticism and alternatives¶
CSS-in-JS is not without controversy:
- Runtime overhead — styles are generated in JavaScript
- Bundle size — styled-components adds ~12KB gzipped
- Learning curve for CSS purists
- Debugging — generated class names are unreadable (resolved by a babel plugin)
Alternatives: CSS Modules (build-time scoping), Emotion (more performant runtime), Glamorous (API inspired by styled-components).
Conclusion: a new standard for React styling¶
styled-components changes the way we think about styling in React applications. For new React projects we recommend CSS-in-JS as the default approach — the productivity and maintenance benefits outweigh the minor drawbacks.
Need help with implementation?
Our experts can help with design, implementation, and operations. From architecture to production.
Contact us