Styled Components / Emotion
Subject: React
Styled Components / Emotion in React — Detailed Guide
📍 What Are Styled Components?
Styled Components is a popular CSS-in-JS library that lets you write actual CSS inside JavaScript.
- Styles are scoped to individual components
 - You use template literals to write clean, readable CSS
 - It supports full CSS — including media queries, animations, pseudo-selectors, and dynamic styling
 
🧠 Emotion is an alternative CSS-in-JS library with a similar syntax and lighter runtime in large teams.
✅ Why Use Styled Components?
| Feature | Benefit | 
|---|---|
| Component-scoped styles | No global class name collisions | 
| Dynamic styling with props | Style changes based on props/state | 
| Full CSS support | Supports media queries, pseudo-selectors | 
| JS + CSS together | Less context switching, better encapsulation | 
| Theming support | Built-in ThemeProvider for global themes | 
🛠️ Setup
🔧 Installation
📦 Emotion (Alternative)
✅ Basic Example: Styled Button
🔍 What Happens Behind the Scenes
Styled Components:
- Generates a unique class name
 - Injects the styles into a 
<style>tag in your document - Ensures styles are scoped, not global
 
✅ Dynamic Styling with Props
✅ Responsive Design
✅ Nesting & Pseudo-Selectors
✅ Example: Complete Card Component
⚠️ Things to Know
| Consideration | Explanation | 
|---|---|
| Bundle size | Slightly heavier than plain CSS | 
| Debugging | Class names are auto-generated (can be long) | 
| SSR support | ✅ Fully supported (e.g., with Next.js) | 
| Tooling | Works well with TypeScript, Jest, Storybook | 
📌 Summary Table
| Feature | Description | 
|---|---|
| `styled.tagName`` | Use styled.button, styled.div, etc. | 
| Dynamic styling | Use props inside template literals | 
| CSS supported | ✅ Media queries, animations, pseudo-selectors | 
| Scoped automatically | No global collisions or overrides | 
| Libraries | styled-components, @emotion/styled | 
🎯 When to Use Styled Components or Emotion
| Ideal For | Less Ideal For | 
|---|---|
| Component-based design systems | Utility class-based projects | 
| Dynamic, theme-based styling | Repetitive/static styles | 
| Avoiding naming conflicts | Projects using global CSS/SCSS | 
💡 Final Tip
For theming, use ThemeProvider from styled-components or Emotion to apply consistent styles across your app.
Advertisement Slot 1
Advertisement Slot 2