Frontend Patterns

Pattern

CSS-in-JS

Write styles in JavaScript to enable dynamic styling and component co-location.

Styling Beginner

CSS-in-JS

Problem

Styles live in separate CSS files disconnected from component logic, making it difficult to pass dynamic values like properties or state into styling. Developers manually toggle classes or inline styles based on conditions, leading to verbose code and maintenance overhead when styling needs to respond to runtime data.

Solution

Write CSS directly in JavaScript using tagged templates or object syntax, generating scoped styles at runtime or build time. This colocates styles with components and enables dynamic styling based on props or state.

Example

This example demonstrates CSS-in-JS using styled components to create dynamic styles based on component props.

// Define a styled component with dynamic styles based on props
const Button = styled.button`
  background: ${props => props.primary ? '#007bff' : '#6c757d'};  // Conditional background color
  color: white;
  padding: 10px 20px;
  border: none;
  border-radius: 4px;
`;

// Use the styled component with props to control appearance
<Button primary>Click me</Button>

Benefits

  • Colocates styles with component logic for better maintainability.
  • Enables truly dynamic styling based on props and state.
  • Automatic scoping prevents style conflicts between components.
  • Can eliminate unused styles automatically with dead code elimination.
  • Full power of JavaScript for computing styles and reusing logic.

Tradeoffs

  • Adds runtime overhead for style injection and computation.
  • Increases bundle size with additional JavaScript library code.
  • Debugging can be harder with generated class names.
  • May fragment team knowledge between CSS and JavaScript developers.
  • Can impact performance if not carefully optimized with memoization.
Stay Updated

Get New Patterns
in Your Inbox

Join thousands of developers receiving weekly insights on frontend architecture patterns

No spam. Unsubscribe anytime.