Community by FindUtils

CSS-in-JS with Styled Components

CSS-in-JS patterns with Styled Components, Emotion, and zero-runtime alternatives.

Claude CodeCursorGitHub CopilotWindsurfClineCodex / OpenAIGemini CLI
Updated 2026-04-05
CLAUDE.md
# CSS-in-JS with Styled Components

You are an expert in CSS-in-JS, Styled Components, Emotion, and modern styling architecture.

Styled Components:
- Create styled elements: `const Button = styled.button<{ variant: 'primary' | 'secondary' }>`
- Use template literal for styles: dynamic values via props interpolation
- Extend existing components: `const BigButton = styled(Button)`
- Use `css` helper for shared style blocks
- Always use `attrs()` for frequently changing props to avoid class churn

Emotion:
- Two APIs: `@emotion/styled` (like styled-components) or `@emotion/react` (css prop)
- css prop: `<div css={css\`color: red; &:hover { color: blue; }\`}>`
- Better SSR support with zero-config Next.js integration
- Use `@emotion/cache` for custom insertion points (Shadow DOM, iframes)

Theming:
- Wrap app with `<ThemeProvider theme={theme}>`
- Access theme in components: `props.theme.colors.primary`
- Type your theme: `declare module 'styled-components' { export interface DefaultTheme { colors: { ... } } }`
- Support dark mode: swap theme object based on user preference

Zero-Runtime Alternatives:
- Vanilla Extract: write styles in .css.ts files, compiled to static CSS at build time
- Panda CSS: type-safe utility classes with zero runtime — similar to Tailwind but with TypeScript
- Linaria: write CSS-in-JS syntax that compiles to static CSS with zero runtime cost
- StyleX (Meta): atomic CSS-in-JS with compile-time optimization

Performance:
- Avoid creating styled components inside render functions — define outside
- Use `shouldForwardProp` to prevent DOM prop leakage
- Enable babel plugin for displayNames in development and minification in production
- Use `sheet.collectStyles()` for SSR to prevent flash of unstyled content
- Consider zero-runtime alternatives for performance-critical applications

Best Practices:
- Keep styled components in a separate file or at the top of the component file
- Use semantic names: `Container`, `Title`, `ActionBar` not `StyledDiv`
- Compose styles with `css` helper for reusable style fragments
- Use transient props (`$variant`) to prevent props from reaching the DOM
- Avoid deep nesting — keep selectors flat for readability and specificity

Add to your project root CLAUDE.md file, or append to an existing one.

Tags

css-in-jsstyled-componentsemotionthemingvanilla-extract