styled-components

Write actual CSS in your React components and let styled-components scope, inject, and dedupe it at runtime.

Library
npm
v6.6.0
41,061 stars
MIT License

Repository Health

Pre-computed score based on development activity, maintenance, community, maturity, and trend momentum. How we score it →
89 /100 Excellent
Development Activity 92
Maintenance 96
Community 68
Maturity 60
Momentum 40

Technical Analysis

AI-assessed by reading the actual repository — architecture, code quality, innovation, and documentation. How we score it →
88 /100 Excellent
Architecture 88
Code Quality 90
Innovation 82
Learning Curve 90

styled-components lets you define component styles as tagged template literals of real CSS, scoped automatically to generated class names so there’s no naming collisions, no separate stylesheet to keep in sync, and no build-step CSS pipeline required. A single API covers client components, server components, streaming SSR, and React Native, with the library detecting the runtime and adjusting its injection strategy accordingly.

Beyond basic styled.div usage, it ships theming via React context (ThemeProvider), a createTheme helper that emits CSS custom properties so themed components keep stable class-name hashes across variants (avoiding hydration mismatches when switching light/dark), keyframes for scoped animations, createGlobalStyle for app-wide resets, attrs for default/computed HTML attributes, and a plugin system (StyleSheetManager + SCPlugin) for vendor-prefixing and custom declaration/selector transforms.

Internally the library parses each component’s CSS once into an AST via a hand-rolled parser (not a general CSS library dependency), then re-evaluates only the dynamic interpolation slots on each render, caching generated class names against a content hash so identical style output is never re-emitted. This is what keeps a JS-in-CSS approach fast enough for React Native and RSC alike, at under 13kB gzipped with no peer build-tool integration.

What You Get

  • Scoped styling via styled.<tag> - write real CSS in a template literal per component; class names are generated and injected automatically, with zero risk of global collisions.
  • Theming with stable hashes - ThemeProvider and createTheme push design tokens through context or CSS custom properties, keeping class-name hashes stable across theme switches to avoid hydration mismatches.
  • Animation primitives - keyframes defines scoped @keyframes blocks you can interpolate directly into a styled component’s animation property.
  • Global styles and resets - createGlobalStyle injects app-wide CSS (resets, font-faces) with the same templating and theming support as component styles.
  • Static/computed attributes via .attrs() - set default HTML attributes, or compute them from props and theme values, without cluttering the JSX call site.
  • A pluggable declaration/selector pipeline - StyleSheetManager accepts an ordered list of SCPlugins (e.g. the built-in prefixPlugin) to rewrite CSS declarations or selectors at emit time.

Common Use Cases

  • Component-scoped design systems - teams building a component library want styles to travel with the component file instead of a separate CSS/SCSS tree.
  • Cross-platform React + React Native codebases - a single styled-components call site targets both web and native rendering paths without maintaining parallel stylesheets.
  • Themeable products with light/dark or multi-brand modes - createTheme’s CSS-variable approach lets an app switch themes at runtime without a page reload or class-name churn.
  • Server-rendered and streaming React apps - Next.js/RSC-style apps that need styles correctly flushed during SSR or streamed alongside server components without FOUC.
  • Third-party component styling - wrapping components from other libraries (e.g. react-router-dom’s Link) that accept a className prop, without editing their source.

Under The Hood

Architecture

The library is organized as a small set of composable layers rather than a monolith: constructors/styled.tsx builds the public styled factory and tag proxies (styled.div, styled(Component)), which hands off to models/StyledComponent.ts (the ~880-line core that creates the actual React component, wires up the render-time cache, and decides between client-buffered injection via useInsertionEffect, synchronous ServerStyleSheet flushing, or RSC-mode inline <style> fragments). Each styled component’s CSS is parsed once into an AST (parser/parser.ts, parser/ast.ts) and only the dynamic interpolation slots are re-evaluated per render (parser/compile.ts’s evaluateForFastPath), with generated class names cached by content hash so unchanged output is never re-emitted. Style injection itself is centralized in sheet/Sheet.ts and sheet/GroupedTag.ts, which manage per-component CSSOM rule groups (CSSStyleSheet.insertRule) and support rehydration from server-rendered markup. docs/rendering-flow.md documents this exact request path as a sequence diagram, kept in sync with the code by convention. What breaks if the core WebStyle/StyleSheet abstraction changes: every render path (client, SSR, streaming, RSC) depends on its generate/inject/flush contract, so the four injection strategies would all need coordinated updates.

Tech Stack

The package is authored in TypeScript (95%+ of the codebase) and built with Rollup into CJS, ESM, and browser-specific bundles, plus a separate React Native entry point built from the same source via native/. It has effectively one runtime dependency, csstype, and treats react, react-dom, and react-native/react-native-reanimated as optional peer dependencies so the same package serves both web and native consumers. The monorepo is managed with pnpm workspaces and Changesets for versioned releases, uses Biome (not ESLint/Prettier) for linting and formatting, and Husky + lint-staged for pre-commit checks; a knip config guards against unused exports.

Code Quality

Testing is extensive and multi-layered: 100+ Jest test files cover web rendering, React Native rendering, SSR, RSC streaming, prop forwarding, theming, plugin behavior, and even dedicated performance benchmark suites (bench/*.bench.test.ts) that assert on render/parse throughput, not just correctness. A separate test:types pass runs a strict TypeScript project against tsconfig.test-types.json to catch type-level regressions in the public API. CI runs CodeQL security analysis on every push/PR in addition to the standard test suite. Source files carry substantial inline documentation explaining non-obvious performance tradeoffs (e.g. why a memo wrapper is hand-constructed instead of calling React.memo()), and the codebase is consistently typed throughout with no evidence of any-laden escape hatches in the core modules reviewed.

What Makes It Unique

Rather than depending on a general-purpose CSS parsing library, styled-components ships its own hand-rolled CSS parser and AST compiler purpose-built for the tagged-template-literal + interpolation shape it needs to support, letting it parse a component’s static CSS structure exactly once and re-evaluate only the dynamic slots on every render — a targeted optimization a generic parser wouldn’t provide. createTheme’s CSS-custom-property approach is a comparatively novel answer to a common CSS-in-JS pain point (theme switches causing hydration mismatches or full re-renders), and the library’s explicit three-way runtime detection (buffered client injection vs. synchronous SSR flush vs. RSC inline-fragment mode) reflects real engineering investment in staying current with React’s evolving rendering models rather than treating SSR/RSC as an afterthought.

Join founders buildingwith open source

Opinionated takes, migration guides, cost-saving tips, and insights from the open source ecosystem.

Subscribe on Substack
Join 750+ subscribers