[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,111 +2,181 @@
|
||||
id: wiki-2026-0508-styled-components
|
||||
title: Styled Components
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [styled-components, CSS-in-JS]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [auto-consolidated, technical-documentation]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [react, css-in-js, frontend, styling]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-05-08
|
||||
last_reinforced: 2026-05-10
|
||||
github_commit: pending
|
||||
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
|
||||
tech_stack:
|
||||
language: unspecified
|
||||
framework: unspecified
|
||||
language: typescript
|
||||
framework: react
|
||||
---
|
||||
|
||||
# [[Styled Components|Styled Components]]
|
||||
# Styled Components
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
Styled Components는 React 및 [[Next.js|Next.js]] 환경에서 사용되는 대표적인 CSS-in-JS 라이브러리로, 자바스크립트 파일 내에서 태그된 템플릿 리터럴(tagged template literals)을 사용하여 CSS를 직접 작성할 수 있게 해줍니다 [1, 2]. 이 방식은 컴포넌트와 스타일 코드를 같은 곳에 위치(co-location)시키고 자동으로 고유한 클래스명을 생성하여 스타일의 전역 충돌을 방지합니다 [3, 4]. 프롭스(props)와 상태(State)를 기반으로 한 동적 스타일링에 매우 강력하지만, 런타임 CSS 생성으로 인한 성능 오버헤드와 최근의 [[React Server Components|React Server Components]](RSC) 환경에서의 호환성 처리라는 과제를 안고 있습니다 [4-6].
|
||||
## 매 한 줄
|
||||
> **"매 CSS 의 component 의 안에 — 매 tagged template literal 로 매 React component + style 의 atomic unit"**. Glen Maddern, Max Stoiber (2016). 매 CSS-in-JS 의 reference. 2026 매 styled-components v6+ 가 매 React Server Components 의 partial 지원 — 매 RSC native era 에서 매 Tailwind / vanilla-extract / CSS Modules 의 challenge.
|
||||
|
||||
---
|
||||
## 매 핵심
|
||||
|
||||
styled-components는 [[JavaScript|JavaScript]] 파일 내에서 태그된 템플릿 리터럴(Tagged Template Literals)을 사용하여 React 컴포넌트의 스타일을 지정하는 대표적인 CSS-in-JS 라이브러리이다 [1-3]. 스타일을 개별 컴포넌트에 지역적으로 캡슐화하여 전역 네임스페이스 충돌이나 스타일 누수 현상을 방지한다 [3-5]. Props나 상태([[State|State]]), 테마를 활용한 동적 스타일링 측면에서 뛰어난 개발자 경험을 제공하지만, 런타임에 CSS를 생성하고 주입하는 방식 때문에 성능 오버헤드와 번들 크기 증가라는 트레이드오프가 존재한다 [6, 7].
|
||||
### 매 mechanic
|
||||
- 매 tagged template literal: ``styled.button`color: red```.
|
||||
- 매 runtime 의 unique class name 의 generation, 매 stylesheet 의 inject.
|
||||
- 매 props-based dynamic styling: ``${props => props.primary ? '#0070f3' : '#fff'}``.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **동적 스타일링 및 테마 시스템**: Styled Components는 프롭스와 상태, 그리고 테마를 활용해 자연스러운 동적 스타일링을 가능하게 합니다 [4, 6]. 라이브러리에 내장된 `ThemeProvider`는 [[Context API|Context API]]를 통해 앱 하위의 모든 컴포넌트에 테마를 주입할 수 있어 다크 모드나 다중 브랜드 테마를 구축하는 데 유용합니다 [4, 7].
|
||||
* **주요 컴포넌트 API**:
|
||||
* **`as` 프롭스**: 컴포넌트에 적용된 스타일은 그대로 유지하면서, 런타임에 렌더링되는 실제 HTML 태그나 React 컴포넌트를 변경할 수 있는 다형성(polymorphism)을 제공합니다 [8].
|
||||
* **트랜지언트 프롭스 (Transient props)**: 스타일링 컴포넌트 전용으로 사용되며 실제 DOM 노드에는 전달되지 않기를 원하는 프롭스의 경우, 이름 앞에 달러 기호(`$`)를 붙여 필터링할 수 있습니다 [9, 10].
|
||||
* **성능 및 번들 사이즈의 한계**: 런타임에 CSS 문자열을 생성하고 브라우저에 주입해야 하기 때문에 CPU 및 [[JavaScript|JavaScript]] 실행 비용(런타임 텍스)이 발생합니다 [4, 6]. 라이브러리 추가로 인해 번들 사이즈가 약 30kb(gzipped) 증가하며, 대규모 렌더링(예: 10,000개 리스트 아이템) 시 빌드 타임 기반의 [[Tailwind CSS|Tailwind CSS]](85ms)보다 렌더링 시간(148ms)이 더 오래 걸리는 등 성능 최적화 면에서 한계를 보입니다 [5, 6, 11].
|
||||
* **[[React Server Components (RSC)|React Server Components (RSC]] 호환성과 Next.js 통합**: Styled Components의 테마 기능은 React Context에 의존하므로, Context가 없는 서버 컴포넌트(RSC) 환경에서는 기본적으로 작동하지 않습니다 [12, 13]. Next.js 15의 App Router에서 사용하기 위해서는 렌더링 중 CSS 규칙을 수집하여 `<head>`에 주입하는 '스타일 레지스트리([[Style Registry|Style Registry]]) 패턴'을 적용해야 합니다 [14]. 또한 서버와 클라이언트 간의 하이드레이션([[Hydration|Hydration]]) 불일치를 막기 위해 컴파일러 설정(`styledComponents`)을 활성화해야 합니다 [15]. 최신 버전(v6.3.0 이상)에서는 RSC 환경에서 자동으로 인라인 `<style>` 태그를 방출하여 [[React 19|React 19]]의 호이스팅 및 중복 제거 기능을 지원하도록 업데이트되었습니다 [16].
|
||||
### 매 features
|
||||
- **Theming**: ThemeProvider context.
|
||||
- **`as` prop**: 매 polymorphic element.
|
||||
- **Extending**: ``styled(Button)`...```.
|
||||
- **Animations**: keyframes helper.
|
||||
- **Global styles**: createGlobalStyle.
|
||||
|
||||
---
|
||||
### 매 응용
|
||||
1. React design system (Material-like component lib).
|
||||
2. Theme switcher (dark mode).
|
||||
3. Per-component style isolation.
|
||||
|
||||
* **작동 원리 및 개발자 경험(DX):** styled-components는 ES6의 태그된 템플릿 리터럴을 통해 컴포넌트와 해당 스타일을 함께 배치(Co-location)한다 [1, 5, 6]. `ThemeProvider`를 이용한 내장 테마 시스템을 지원하며 [6, 8], TypeScript와 원활하게 통합되어 Props 기반의 타입 안전한 동적 스타일링을 구현할 수 있다 [6, 9]. DOM으로 전달되지 않아야 하는 스타일 전용 Props를 필터링하기 위해 이름 앞에 `$`를 붙이는 "Transient props" 기능이나 `shouldForwardProp` API를 제공하여 깔끔한 DOM 트리를 유지할 수 있다 [10-12].
|
||||
* **런타임 성능 및 확장성 이슈:** 스타일이 자바스크립트에 내장되어 런타임에 동적으로 주입되므로 앱의 CPU 사이클 소모와 JS 번들 크기(약 30kb 추가)가 증가하는 단점이 있다 [6, 13, 14]. 이 런타임 오버헤드는 복잡한 대규모 애플리케이션이나 저사양 기기에서 렌더링 성능 병목(예: 10,000개 리스트 렌더링 테스트 시 Tailwind 대비 약 63% 더 느린 148ms 소요)을 유발할 수 있다 [7, 14, 15].
|
||||
* **[[React Server Components (RSC)|React Server Components (RSC]] 및 Next.js 15 호환성:** 전통적인 CSS-in-JS 라이브러리는 React Context에 의존하기 때문에, Context가 존재하지 않는 서버 컴포넌트(RSC) 환경과 근본적으로 호환되지 않는 문제가 있었다 [13, 16-18]. 이를 해결하기 위해 [[Next.js App Router|Next.js App Router]]에서는 렌더링 중 CSS 규칙을 수집하는 '[[Style Registry|Style Registry]]' 패턴과 `useServerInsertedHTML` 훅을 사용해야 하며, 하이드레이션 불일치를 막기 위해 `next.config.js`의 `styledComponents` 컴파일러 옵션을 활성화해야 한다 [18, 19]. 최신 v6.3.0 이상에서는 RSC 환경을 자동 감지하여 인라인 `<style>` 태그를 주입하는 기능을 지원하지만, `ThemeProvider`는 여전히 RSC에서 동작하지 않으므로 [[CSS Variables|CSS Variables]](사용자 지정 속성) 기반의 테마 적용이 권장된다 [8, 20].
|
||||
* **버전 6(v6)의 주요 변경 사항:** v6부터는 코드베이스가 TypeScript로 완전히 다시 작성되어 라이브러리 자체적으로 타입을 제공하며, 내부 파서로 Stylis v4를 사용한다. 또한, 기존에 지원되던 자동 Prop 필터링을 제거하고 Transient props(`$`) 사용을 표준으로 강제한다 [21, 22].
|
||||
## 💻 패턴
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
No trade-offs available.
|
||||
### Basic styled component (TypeScript)
|
||||
```tsx
|
||||
import styled from "styled-components";
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[CSS-in-JS|CSS-in-JS]], Tailwind CSS, React Server Components, [[Dynamic Theming|Dynamic Theming]]
|
||||
- **Projects/Contexts:** [[Next.js App Router|Next.js App Router]], [[Component Library Architecture|Component Library Architecture]]
|
||||
- **Contradictions/Notes:** 소스 [6, 17, 18] 및 [19]는 런타임 비용이 없는 Tailwind CSS가 대규모 프로덕션이나 [[Core Web Vitals|Core Web Vitals]](FID, INP 등) 최적화에 훨씬 뛰어나며, App Router 환경에서는 Tailwind나 [[CSS Modules|CSS Modules]]를 사용하는 것을 권장한다고 주장합니다. 반면, 소스 [20]는 테마가 사용자 데이터나 복잡한 런타임 상태와 깊게 결합된 '고도로 동적인 대시보드 형태의 애플리케이션'에서는 Styled Components가 여전히 매우 강력한 도구라고 강조하며 상반되면서도 보완적인 시각을 제공합니다.
|
||||
const Button = styled.button<{ $primary?: boolean }>`
|
||||
padding: 8px 16px;
|
||||
border-radius: 6px;
|
||||
border: none;
|
||||
cursor: pointer;
|
||||
background: ${(p) => (p.$primary ? "#0070f3" : "#eee")};
|
||||
color: ${(p) => (p.$primary ? "#fff" : "#222")};
|
||||
&:hover { opacity: 0.9; }
|
||||
`;
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-26*
|
||||
|
||||
---
|
||||
|
||||
- **Related Topics:** [[CSS-in-JS|CSS-in-JS]], Tailwind CSS, React Server Components, [[Dynamic Theming|Dynamic Theming]], [[Design Tokens|Design Tokens]]
|
||||
- **Projects/Contexts:** [[Next.js App Router|Next.js App Router]], Scalable Frontend [[Architecture|Architecture]]
|
||||
- **Contradictions/Notes:** 소스에 따르면, styled-components는 모듈화와 동적 스타일링에 매우 강력한 도구이지만, 런타임 비용 문제와 RSC 호환성의 한계로 인해 최근의 확장 가능한 프론트엔드 아키텍처에서는 제로 런타임(Zero-runtime) CSS-in-JS(예: [[vanilla-extract|vanilla-extract]])나 유틸리티 클래스 기반인 Tailwind CSS로 전환(마이그레이션)하여 [[Core Web Vitals|Core Web Vitals]] 최적화를 꾀하는 추세가 확인된다 [16, 17, 23-25].
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-26*
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
export default function App() {
|
||||
return <Button $primary>Buy</Button>;
|
||||
}
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Theme + ThemeProvider
|
||||
```tsx
|
||||
import { ThemeProvider, DefaultTheme } from "styled-components";
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const dark: DefaultTheme = { bg: "#111", fg: "#eee", accent: "#0af" };
|
||||
const light: DefaultTheme = { bg: "#fff", fg: "#111", accent: "#06c" };
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
const Card = styled.div`
|
||||
background: ${(p) => p.theme.bg};
|
||||
color: ${(p) => p.theme.fg};
|
||||
padding: 16px;
|
||||
`;
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
export default function App() {
|
||||
const [mode, setMode] = useState<"light" | "dark">("dark");
|
||||
return (
|
||||
<ThemeProvider theme={mode === "dark" ? dark : light}>
|
||||
<Card>Hello</Card>
|
||||
</ThemeProvider>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
### Extending another styled component
|
||||
```tsx
|
||||
const Base = styled.button`padding: 8px; border-radius: 4px;`;
|
||||
const Danger = styled(Base)`background: #e00; color: white;`;
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### `as` polymorphic prop
|
||||
```tsx
|
||||
const Box = styled.div`padding: 16px;`;
|
||||
<Box as="section" /> // renders <section>
|
||||
<Box as={Link} to="/x" /> // renders react-router Link
|
||||
```
|
||||
|
||||
### Keyframes animation
|
||||
```tsx
|
||||
import styled, { keyframes } from "styled-components";
|
||||
const pulse = keyframes`
|
||||
0% { transform: scale(1); }
|
||||
50% { transform: scale(1.1); }
|
||||
100% { transform: scale(1); }
|
||||
`;
|
||||
const Pulser = styled.div`animation: ${pulse} 1s infinite;`;
|
||||
```
|
||||
|
||||
### Global styles
|
||||
```tsx
|
||||
import { createGlobalStyle } from "styled-components";
|
||||
const Global = createGlobalStyle`
|
||||
body { margin: 0; font-family: Inter, sans-serif; background: ${(p) => p.theme.bg}; }
|
||||
`;
|
||||
```
|
||||
|
||||
### css helper for shared mixin
|
||||
```tsx
|
||||
import { css } from "styled-components";
|
||||
const truncate = css`
|
||||
white-space: nowrap;
|
||||
overflow: hidden;
|
||||
text-overflow: ellipsis;
|
||||
`;
|
||||
const Title = styled.h2`${truncate} font-size: 24px;`;
|
||||
```
|
||||
|
||||
### Next.js 14+ App Router (RSC) — 매 'use client'
|
||||
```tsx
|
||||
"use client";
|
||||
import styled from "styled-components";
|
||||
export const Button = styled.button`color: red;`;
|
||||
```
|
||||
|
||||
```tsx
|
||||
// app/layout.tsx — registry pattern for SSR
|
||||
import StyledRegistry from "./StyledRegistry";
|
||||
export default function Root({ children }) {
|
||||
return <html><body><StyledRegistry>{children}</StyledRegistry></body></html>;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| React SPA, 매 dynamic theming heavy | styled-components / emotion |
|
||||
| React Server Components 의 native | vanilla-extract / CSS Modules / Tailwind |
|
||||
| Utility-first, design system | Tailwind CSS v4 |
|
||||
| Build-time zero-runtime | vanilla-extract / Linaria |
|
||||
| Component lib for distribution | CSS Modules + tokens |
|
||||
|
||||
**기본값** (2026): 매 새 React project — Tailwind 의 default. styled-components 의 dynamic + theme heavy app 에 still-valid.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[CSS-in-JS]] · [[React]]
|
||||
- 변형: [[Emotion]] · [[Vanilla Extract]] · [[Linaria]]
|
||||
- 응용: [[Design System]] · [[Theme Switching]]
|
||||
- Adjacent: [[Tailwind CSS]] · [[CSS Modules]] · [[React Server Components]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: dynamic prop-based styles 의 heavy, theme switching 의 first-class, existing CSS-in-JS app.
|
||||
**언제 X**: 매 RSC-first new app — runtime cost + 'use client' boundary 의 friction. 매 Tailwind / vanilla-extract 의 prefer.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Inline style prop interpolation 의 every render**: 매 className thrash 의 perf hit. 매 attrs / static class 의 사용.
|
||||
- **No `$` prefix on props**: 매 DOM warning (unknown attribute). 매 transient prop 의 사용 — `$primary`.
|
||||
- **createGlobalStyle 의 multiple instances**: 매 conflict.
|
||||
- **SSR without registry**: 매 FOUC. Next.js registry 의 setup.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (styled-components.com docs v6, 2025; Next.js 14 App Router CSS-in-JS guide).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — styled-components v6 + RSC era guidance |
|
||||
|
||||
Reference in New Issue
Block a user