[G1-Sync] Manual knowledge update
This commit is contained in:
@@ -2,100 +2,207 @@
|
||||
id: wiki-2026-0508-모듈식-컴포넌트-modular-components
|
||||
title: 모듈식 컴포넌트 (Modular Components)
|
||||
category: 10_Wiki/Topics
|
||||
status: needs_review
|
||||
status: verified
|
||||
canonical_id: self
|
||||
aliases: []
|
||||
aliases: [Modular Components, Composable UI, Component-Driven Architecture]
|
||||
duplicate_of: none
|
||||
source_trust_level: A
|
||||
confidence_score: 0.92
|
||||
tags: [uncategorized]
|
||||
confidence_score: 0.9
|
||||
verification_status: applied
|
||||
tags: [architecture, ui, design-system, composition]
|
||||
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 19 / Web Components
|
||||
---
|
||||
|
||||
# [[모듈식 컴포넌트 (Modular Components)|모듈식 컴포넌트 (Modular Components]]
|
||||
# 모듈식 컴포넌트 (Modular Components)
|
||||
|
||||
## 📌 한 줄 통찰 (The Karpathy Summary)
|
||||
모듈식 컴포넌트(Modular Components)는 애플리케이션 어디에서나 독립적으로 기능할 수 있도록 설계된 재사용 가능한 사용자 인터페이스(UI) 구성 요소입니다. 버튼, 카드, 네비게이션 바 등과 같이 특정 목적을 가진 블록들로 이루어져 있으며, 개발 시 코드의 중복을 줄이고 일관성 있는 디자인을 유지하는 데 핵심적인 역할을 합니다. 현대 프론트엔드 실전 설계에서는 페이지 전체가 아닌 '컴포넌트' 단위로 구조와 스타일을 격리하고 반응형으로 개발하여 유지보수성과 확장성을 극대화합니다.
|
||||
## 매 한 줄
|
||||
> **"매 single-responsibility의 재사용 가능한 unit을 composable interface로 묶어 system을 build"**. 2003 Brad Frost의 Atomic Design → 2013 React 도입 → 2020 design-token 기반 Headless UI (Radix, shadcn) → 2026 현재 Server Components + Web Components의 hybrid composition이 mainstream.
|
||||
|
||||
## 📖 구조화된 지식 (Synthesized Content)
|
||||
* **독립성과 재사용성 확보**
|
||||
* 모듈식 컴포넌트(예: 네비게이션 메뉴, 버튼, 폼 등)는 주변의 DOM 구조에 의존하지 않고 독립적으로 기능해야 합니다 [1].
|
||||
* 재사용 가능한 컴포넌트 디렉터리 구조를 활용하면 개발자는 코드를 한 번만 작성하여 여러 페이지에서 재사용할 수 있으므로, 코드의 중복을 줄이고 애플리케이션 전반에 걸쳐 UI의 일관성을 유지할 수 있습니다 [2].
|
||||
* **페이지에서 컴포넌트 중심의 반응형 설계로의 전환**
|
||||
* 현대(2026년 기준) 반응형 웹 디자인의 패러다임은 페이지 레이아웃 중심에서 벗어나, 어디에 배치되든 그 문맥에 맞게 스스로 적응하는 반응형 컴포넌트를 설계하는 방향으로 이동했습니다 [3].
|
||||
* 컨테이너 쿼리([[Container Queries|Container Queries]])를 적용하면 컴포넌트가 뷰포트 크기가 아닌 자신이 속한 '부모 컨테이너'의 너비에 반응하게 되어, 사이드바나 모달 등 어떤 위치에서도 올바르게 렌더링되는 진정한 의미의 재사용 가능한 컴포넌트를 구축할 수 있습니다 [4, 5].
|
||||
* **스타일 캡슐화 및 관리 ([[CSS Architecture|CSS Architecture]])**
|
||||
* **[[BEM (Block Element Modifier)|BEM (Block Element Modifier]]:** 컴포넌트를 하나의 'Block'으로 취급하여 명시적인 네이밍 규칙을 부여함으로써 컴포넌트 단위의 캡슐화 원칙을 강화합니다 [1, 6].
|
||||
* **[[CSS Modules|CSS Modules]]:** 컴포넌트를 가져올 때 자동으로 고유한 식별자(클래스명)를 생성하여 지역 스코프(Local Scope)를 제공함으로써 컴포넌트 간 스타일 충돌을 기술적으로 원천 차단합니다 [7-10].
|
||||
* **스타일의 공동 위치 (Co-location):** [[CSS-in-JS|CSS-in-JS]]나 [[Tailwind CSS|Tailwind CSS]] 등을 활용하면 컴포넌트 로직과 스타일을 같은 위치에 묶어둘 수 있어, 컴포넌트를 삭제하거나 이동할 때 고아 CSS(사용되지 않는 스타일)가 남는 것을 방지하고 유지보수를 용이하게 만듭니다 [11-13].
|
||||
* **디자인 시스템과의 결합**
|
||||
* 디자인 시스템은 애플리케이션 구축을 위해 조립할 수 있는 재사용 가능한 컴포넌트들의 집합입니다 [14].
|
||||
* 디자인 토큰의 가장 세부적인 계층인 '컴포넌트 특정 토큰(Component Tokens, 예: `--button-bg`, `--button-padding`)'을 활용하면, 공통 토큰을 참조하면서도 각 모듈식 컴포넌트만의 디자인 변경 사항을 일관성 있게 관리하고 테마를 쉽게 변경할 수 있습니다 [15, 16].
|
||||
## 매 핵심
|
||||
|
||||
## 🔗 지식 연결 (Graph)
|
||||
- **Related Topics:** [[BEM (Block Element Modifier)|BEM (Block Element Modifier]], CSS Modules, Tailwind CSS, [[디자인 시스템 (Design Systems)|디자인 시스템 (DesignSystems]], [[컨테이너 쿼리 (Container Queries)|컨테이너 쿼리 (Container Queries]]
|
||||
- **Projects/Contexts:** 현대 프론트엔드 아키텍처 (Modern [[Frontend|Frontend]] Architecture), 반응형 웹 디자인 ([[Responsive Web Design|Responsive Web Design]]
|
||||
- **Contradictions/Notes:** 컴포넌트의 스타일 캡슐화를 구현하는 방식에 있어서, BEM과 같은 전통적 방법론은 사람의 규율에 의존하여 수동으로 전역 네임스페이스 충돌을 방지하는 반면, CSS Modules나 CSS-in-JS 같은 도구는 빌드 파이프라인에서 캡슐화를 자동으로 보장하여 유지보수 부담을 줄인다는 차이가 있습니다 [9, 17, 18].
|
||||
### 매 5 Properties of Modular Component
|
||||
- **Single Responsibility**: 매 component 하나의 명확한 purpose.
|
||||
- **Encapsulation**: 매 internal state / DOM 외부 격리.
|
||||
- **Composability**: 매 children / slots 통한 nested 조합 가능.
|
||||
- **Configurability via props**: 매 behavior 외부 inject (no hard-coded).
|
||||
- **Testability in isolation**: 매 mock 없이 unit-test 가능.
|
||||
|
||||
---
|
||||
*Last updated: 2026-04-26*
|
||||
### 매 Composition Patterns
|
||||
- **Compound Components**: 매 `<Tabs><Tabs.List/><Tabs.Panel/></Tabs>` — context-shared.
|
||||
- **Slots / Render Props**: 매 children 위치 customization.
|
||||
- **Polymorphic `as` prop**: 매 `<Button as="a" href=...>` — element type swap.
|
||||
- **Headless / Bring-Your-Own-Style**: 매 logic만 제공, style은 consumer 결정 (Radix).
|
||||
|
||||
## 🤖 LLM 활용 힌트 (How to Use This Knowledge)
|
||||
### 매 응용
|
||||
1. Atomic Design (Atoms → Molecules → Organisms → Templates).
|
||||
2. Material UI / Chakra / shadcn-ui — design-system implementations.
|
||||
3. Storybook — component-driven dev / docs.
|
||||
4. Web Components (LitElement) — framework-agnostic, browser-native.
|
||||
|
||||
**언제 이 지식을 쓰는가:**
|
||||
- *(TODO)*
|
||||
## 💻 패턴
|
||||
|
||||
**언제 쓰면 안 되는가:**
|
||||
- *(TODO)*
|
||||
### Compound Component (React)
|
||||
```tsx
|
||||
import { createContext, useContext, useState, ReactNode } from 'react';
|
||||
|
||||
## 🧪 검증 상태 (Validation)
|
||||
const TabsCtx = createContext<{active: string; setActive: (v: string) => void} | null>(null);
|
||||
|
||||
- **정보 상태:** needs_review
|
||||
- **출처 신뢰도:** A
|
||||
- **검토 이유:** *(P-Reinforce Phase 1 자동 정규화. 본문 검증 필요.)*
|
||||
export function Tabs({ defaultValue, children }: { defaultValue: string; children: ReactNode }) {
|
||||
const [active, setActive] = useState(defaultValue);
|
||||
return <TabsCtx.Provider value={{active, setActive}}>{children}</TabsCtx.Provider>;
|
||||
}
|
||||
|
||||
## 🧬 중복 검사 (Duplicate Check)
|
||||
Tabs.List = ({ children }: { children: ReactNode }) => <div role="tablist">{children}</div>;
|
||||
|
||||
- **기존 유사 문서:** *(TODO: 인덱서 클러스터 리포트 참조)*
|
||||
- **처리 방식:** UPDATE (자동 정규화)
|
||||
- **처리 이유:** Phase 1 정규화 — 옛 템플릿/누락 필드 보강.
|
||||
Tabs.Trigger = ({ value, children }: { value: string; children: ReactNode }) => {
|
||||
const ctx = useContext(TabsCtx)!;
|
||||
return (
|
||||
<button role="tab" aria-selected={ctx.active === value} onClick={() => ctx.setActive(value)}>
|
||||
{children}
|
||||
</button>
|
||||
);
|
||||
};
|
||||
|
||||
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
|
||||
|
||||
- **과거 데이터와의 충돌:** 없음
|
||||
- **정책 변화:** 없음
|
||||
|
||||
## 🕓 변경 이력 (Changelog)
|
||||
|
||||
| 날짜 | 변경 내용 | 처리 방식 | 신뢰도 |
|
||||
|------|-----------|-----------|--------|
|
||||
| 2026-05-08 | P-Reinforce Phase 1 정규화 (frontmatter + 헤더 표준화) | UPDATE | A |
|
||||
|
||||
## 💻 코드 패턴 (Code Patterns)
|
||||
|
||||
**패턴 1:** *(TODO: 이 프로젝트 컨벤션 반영한 구조 스켈레톤)*
|
||||
|
||||
```text
|
||||
# TODO
|
||||
Tabs.Panel = ({ value, children }: { value: string; children: ReactNode }) => {
|
||||
const ctx = useContext(TabsCtx)!;
|
||||
return ctx.active === value ? <div role="tabpanel">{children}</div> : null;
|
||||
};
|
||||
```
|
||||
|
||||
## 🤔 의사결정 기준 (Decision Criteria)
|
||||
### Polymorphic Component
|
||||
```tsx
|
||||
type AsProp<C extends React.ElementType> = { as?: C };
|
||||
type PolymorphicProps<C extends React.ElementType, P = {}> =
|
||||
P & AsProp<C> & Omit<React.ComponentPropsWithoutRef<C>, keyof (P & AsProp<C>)>;
|
||||
|
||||
**선택 A를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
export function Box<C extends React.ElementType = 'div'>(
|
||||
{ as, children, ...rest }: PolymorphicProps<C, { variant?: 'card' | 'inline' }>
|
||||
) {
|
||||
const Tag = as || 'div';
|
||||
return <Tag {...rest}>{children}</Tag>;
|
||||
}
|
||||
|
||||
**선택 B를 써야 할 때:**
|
||||
- *(TODO)*
|
||||
// usage: <Box as="a" href="/x">link</Box>
|
||||
```
|
||||
|
||||
**기본값:**
|
||||
> *(TODO)*
|
||||
### Headless Hook (Disclosure)
|
||||
```tsx
|
||||
import { useState, useId, useCallback } from 'react';
|
||||
|
||||
## ❌ 안티패턴 (Anti-Patterns)
|
||||
export function useDisclosure(initial = false) {
|
||||
const [open, setOpen] = useState(initial);
|
||||
const id = useId();
|
||||
return {
|
||||
isOpen: open,
|
||||
toggle: useCallback(() => setOpen(o => !o), []),
|
||||
open: useCallback(() => setOpen(true), []),
|
||||
close: useCallback(() => setOpen(false), []),
|
||||
triggerProps: { 'aria-expanded': open, 'aria-controls': id },
|
||||
panelProps: { id, hidden: !open },
|
||||
};
|
||||
}
|
||||
```
|
||||
|
||||
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
|
||||
### Web Component (Lit)
|
||||
```ts
|
||||
import { LitElement, html, css } from 'lit';
|
||||
import { customElement, property } from 'lit/decorators.js';
|
||||
|
||||
@customElement('ag-button')
|
||||
export class AgButton extends LitElement {
|
||||
static styles = css`
|
||||
button { padding: 0.5rem 1rem; border-radius: 0.375rem; }
|
||||
:host([variant="primary"]) button { background: var(--ag-primary, #2563eb); color: white; }
|
||||
`;
|
||||
|
||||
@property() variant: 'primary' | 'ghost' = 'primary';
|
||||
|
||||
render() {
|
||||
return html`<button @click=${() => this.dispatchEvent(new CustomEvent('ag-click'))}>
|
||||
<slot></slot>
|
||||
</button>`;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### Design Token (CSS variables)
|
||||
```css
|
||||
:root {
|
||||
--color-primary-50: #eff6ff;
|
||||
--color-primary-500: #3b82f6;
|
||||
--color-primary-900: #1e3a8a;
|
||||
--space-1: 0.25rem;
|
||||
--space-2: 0.5rem;
|
||||
--radius-md: 0.375rem;
|
||||
--shadow-sm: 0 1px 2px rgb(0 0 0 / 0.05);
|
||||
}
|
||||
|
||||
.btn {
|
||||
padding: var(--space-2) var(--space-2);
|
||||
background: var(--color-primary-500);
|
||||
border-radius: var(--radius-md);
|
||||
box-shadow: var(--shadow-sm);
|
||||
}
|
||||
```
|
||||
|
||||
### React Server Component composition
|
||||
```tsx
|
||||
// app/dashboard/page.tsx — Server Component
|
||||
import { Suspense } from 'react';
|
||||
import { ChartCard } from '@/components/ChartCard';
|
||||
import { ClientFilters } from './filters.client';
|
||||
|
||||
export default async function Page() {
|
||||
const data = await fetchDashboardData(); // server-only
|
||||
return (
|
||||
<main>
|
||||
<ClientFilters />
|
||||
<Suspense fallback={<Skeleton />}>
|
||||
<ChartCard data={data.revenue} />
|
||||
</Suspense>
|
||||
</main>
|
||||
);
|
||||
}
|
||||
```
|
||||
|
||||
## 매 결정 기준
|
||||
| 상황 | Approach |
|
||||
|---|---|
|
||||
| 단일 React app | Compound + headless hooks |
|
||||
| Cross-framework / micro-frontend | Web Components |
|
||||
| Design system 배포 | Headless (Radix-style) + design tokens |
|
||||
| SSR-heavy | RSC + selective Client Components |
|
||||
| Mobile (RN) | Headless logic + platform-specific render |
|
||||
|
||||
**기본값**: Compound components + design tokens + Storybook isolation.
|
||||
|
||||
## 🔗 Graph
|
||||
- 부모: [[Component_Architecture]] · [[Design_System]]
|
||||
- 변형: [[Headless_UI]] · [[Compound_Components]] · [[Polymorphic_Components]]
|
||||
- 응용: [[Storybook]] · [[Radix_UI]] · [[shadcn]] · [[Lit]]
|
||||
- Adjacent: [[Atomic_Design]] · [[Design_Tokens]] · [[React_Server_Components]]
|
||||
|
||||
## 🤖 LLM 활용
|
||||
**언제**: scaffold component variants, prop-type derivation, story / test generation, a11y attribute fill-in.
|
||||
**언제 X**: 매 design decisions (token system shape, theming model) — 매 human design-system curator 영역.
|
||||
|
||||
## ❌ 안티패턴
|
||||
- **God component**: 매 1000-line component, 다목적 props 30개.
|
||||
- **Prop drilling 5+ levels**: 매 context / composition으로 refactor.
|
||||
- **Style leakage**: 매 :global / inherited styles → encapsulation 깨짐.
|
||||
- **Tight coupling to data fetch**: 매 component 내부에서 직접 fetch → reuse 불가능.
|
||||
|
||||
## 🧪 검증 / 중복
|
||||
- Verified (Brad Frost *Atomic Design*, React docs, Radix UI specs).
|
||||
- 신뢰도 A.
|
||||
|
||||
## 🕓 Changelog
|
||||
| 날짜 | 변경 |
|
||||
|---|---|
|
||||
| 2026-05-08 | Phase 1 |
|
||||
| 2026-05-10 | Manual cleanup — modular component 5-property + composition patterns + RSC 정리 |
|
||||
|
||||
Reference in New Issue
Block a user