[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -1,89 +1,173 @@
|
||||
---
|
||||
id: wiki-2026-0508-component-composition
|
||||
title: Component Composition
|
||||
title: Component Composition (React)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: [FE-REACT-COMP-001]
|
||||
aliases: [React Composition, Compound Components]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 1.0
|
||||
tags: [react, Frontend, component-composition, reusability, Modularity, design-patterns, clean-code]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [react, composition, component-design, frontend]
|
||||
raw_sources: []
|
||||
last_reinforced: 2026-04-26
|
||||
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 19
|
||||
---
|
||||
|
||||
# Component Composition (컴포넌트 합성)
|
||||
# Component Composition (React)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
> "상속(Inheritance)의 경직성 대신 합성(Composition)의 유연함을 선택하여, 작고 독립적인 컴포넌트들을 마치 레고 블록처럼 조합함으로써 거대하고 복잡한 시스템을 관리 가능한 수준으로 유지하라" — React 아키텍처의 핵심 설계 원칙 중 하나.
|
||||
## 매 한 줄
|
||||
> **"매 inheritance 의 X, composition 의 O"**. React 의 design principle — UI 를 작은 composable component 로 분해, props.children + slot pattern + compound API 로 매 flexible 한 reuse 달성.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
- **추출된 패턴:** "Containment and Specialization" — 자식 컴포넌트를 `props.children`으로 전달받아 렌더링하는 컨테인먼트 패턴과, 일반적인 컴포넌트를 구체적인 사례로 설정하는 특수화 패턴의 결합.
|
||||
- **주요 구현 기법:**
|
||||
- **Props.children:** 컴포넌트 내부의 구멍(Slot)을 열어두어 호출부에서 자유롭게 UI를 주입하게 함.
|
||||
- **[[Render Props|Render Props]]:** 함수를 prop으로 전달하여 렌더링 로직을 외부에서 결정하게 함.
|
||||
- **HOC (High-Order Components):** 컴포넌트를 인자로 받아 기능을 강화된 새 컴포넌트를 반환 (최근에는 Custom Hooks로 많이 대체됨).
|
||||
- **의의:** 컴포넌트 간의 결합도를 낮추고(Decoupling), 비즈니스 로직과 UI 로직을 명확히 분리하여 코드의 재사용성과 테스트 용이성을 극대화함.
|
||||
## 매 핵심
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
- **과거 데이터와의 충돌:** 과거 객체지향 기반 프레임워크는 클래스 상속을 권장했으나, React 정책은 '상속보다 합성(Composition over Inheritance)' 정책을 절대적 원칙으로 고수함.
|
||||
- **정책 변화:** Antigravity 프로젝트는 모든 공용 UI 라이브러리 설계 시 '슬롯 기반 합성(Slot-based Composition)' 아키텍처를 강제하며, 3단계 이상의 깊은 [[Prop Drilling|Prop Drilling]]이 발생하는 경우 반드시 합성을 통해 구조를 재설계하도록 함.
|
||||
### 매 핵심 idioms
|
||||
- `props.children` (default slot).
|
||||
- Named slots (props as render fn / ReactNode).
|
||||
- Compound components (parent + children share context).
|
||||
- Render props / function-as-children.
|
||||
- Polymorphic `as` prop.
|
||||
- `React.cloneElement` / `Slot` (Radix).
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- React-[[Architecture|Architecture]], [[Custom-Hooks-Patterns|Custom-Hooks-Patterns]], Reusable-UI-Components, Scalable-React-Architecture
|
||||
- **Raw Source:** 00_Raw/Component Composition.md
|
||||
### 매 vs Inheritance
|
||||
- React 매 class extension 의 X — 매 wrapper component.
|
||||
- 매 `<Parent>` + `<Parent.Item>` style 매 implicit relation expression.
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Modal / Dialog (Header / Body / Footer slots).
|
||||
2. Form fields (Field / Label / Input / Error).
|
||||
3. Menu / Combobox (Radix-style headless).
|
||||
4. Layout primitives (Stack, Grid).
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(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
|
||||
### Children as default slot
|
||||
```tsx
|
||||
function Card({ children }: { children: React.ReactNode }) {
|
||||
return <div className="card">{children}</div>;
|
||||
}
|
||||
// <Card><h2>Hi</h2><p>Body</p></Card>
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Named slots via props
|
||||
```tsx
|
||||
type Props = {
|
||||
header?: React.ReactNode;
|
||||
footer?: React.ReactNode;
|
||||
children: React.ReactNode;
|
||||
};
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
function Page({ header, footer, children }: Props) {
|
||||
return (
|
||||
<>
|
||||
{header && <header>{header}</header>}
|
||||
<main>{children}</main>
|
||||
{footer && <footer>{footer}</footer>}
|
||||
</>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
### Compound components with Context
|
||||
```tsx
|
||||
import { createContext, useContext, useState } from 'react';
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
const TabsCtx = createContext<{ active: string; set: (v: string) => void } | null>(null);
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
function Tabs({ defaultValue, children }: { defaultValue: string; children: React.ReactNode }) {
|
||||
const [active, set] = useState(defaultValue);
|
||||
return <TabsCtx value={{ active, set }}>{children}</TabsCtx>;
|
||||
}
|
||||
function Tab({ value, children }: { value: string; children: React.ReactNode }) {
|
||||
const { active, set } = useContext(TabsCtx)!;
|
||||
return <button data-active={active === value} onClick={() => set(value)}>{children}</button>;
|
||||
}
|
||||
function Panel({ value, children }: { value: string; children: React.ReactNode }) {
|
||||
const { active } = useContext(TabsCtx)!;
|
||||
return active === value ? <div>{children}</div> : null;
|
||||
}
|
||||
Tabs.Tab = Tab;
|
||||
Tabs.Panel = Panel;
|
||||
export { Tabs };
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
// Usage:
|
||||
// <Tabs defaultValue="a"><Tabs.Tab value="a">A</Tabs.Tab><Tabs.Panel value="a">…</Tabs.Panel></Tabs>
|
||||
```
|
||||
|
||||
### Render prop
|
||||
```tsx
|
||||
function Toggle({ children }: { children: (state: { on: boolean; toggle: () => void }) => React.ReactNode }) {
|
||||
const [on, setOn] = useState(false);
|
||||
return <>{children({ on, toggle: () => setOn((v) => !v) })}</>;
|
||||
}
|
||||
// <Toggle>{({ on, toggle }) => <button onClick={toggle}>{on ? 'on' : 'off'}</button>}</Toggle>
|
||||
```
|
||||
|
||||
### Polymorphic `as` prop
|
||||
```tsx
|
||||
type AsProp<T extends React.ElementType> = { as?: T } & React.ComponentPropsWithoutRef<T>;
|
||||
|
||||
function Box<T extends React.ElementType = 'div'>({ as, ...rest }: AsProp<T>) {
|
||||
const Tag = as ?? 'div';
|
||||
return <Tag {...rest} />;
|
||||
}
|
||||
// <Box as="section" className="x">…</Box>
|
||||
```
|
||||
|
||||
### Radix Slot pattern (asChild)
|
||||
```tsx
|
||||
import { Slot } from '@radix-ui/react-slot';
|
||||
|
||||
function Button({ asChild, ...props }: { asChild?: boolean } & React.ComponentProps<'button'>) {
|
||||
const Comp = asChild ? Slot : 'button';
|
||||
return <Comp className="btn" {...props} />;
|
||||
}
|
||||
// <Button asChild><a href="/x">link styled as button</a></Button>
|
||||
```
|
||||
|
||||
### Layout primitives (Stack)
|
||||
```tsx
|
||||
function Stack({ gap = 8, children }: { gap?: number; children: React.ReactNode }) {
|
||||
return <div style={{ display: 'flex', flexDirection: 'column', gap }}>{children}</div>;
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Pattern |
|
||||
|---|---|
|
||||
| Single content area | `children` |
|
||||
| Multiple structured slots | Named props or compound |
|
||||
| Tightly-coupled siblings | Compound + context |
|
||||
| Behavior + UI separation | Render props / hook |
|
||||
| Style polymorphism | `as` prop or `Slot` |
|
||||
|
||||
**기본값**: 매 children prop 으로 시작 → 복잡해지면 compound + context.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[React]] · [[Component-Design]]
|
||||
- 변형: [[Vue-Slots]] · [[Svelte-Snippets]] · [[Web-Components]]
|
||||
- 응용: [[Radix-UI]] · [[Headless-UI]] · [[shadcn]]
|
||||
- Adjacent: [[Hooks]] · [[Server-Components]] · [[Composition API]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: design system 구축, library API 설계, complex form/dialog UI.
|
||||
**언제 X**: 매 trivial leaf component — over-engineering.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **Prop explosion**: 매 20+ props → 매 compound 로 분해.
|
||||
- **`cloneElement` everywhere**: 매 fragile, prefer context.
|
||||
- **Deep prop drilling**: 매 context or compound 로 해결.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (react.dev / Radix UI patterns / Kent Dodds blog).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — React composition idioms + compound pattern |
|
||||
|
||||
Reference in New Issue
Block a user