[G1-Sync] Manual knowledge update

This commit is contained in:
Antigravity Agent
2026-05-10 22:08:15 +09:00
parent 21ac3ed255
commit 504fd5fb42
3011 changed files with 380280 additions and 206977 deletions
@@ -2,92 +2,187 @@
id: wiki-2026-0508-프론트엔드-컴포넌트-구조화
title: 프론트엔드 컴포넌트 구조화
category: 10_Wiki/Topics
status: needs_review
status: verified
canonical_id: self
aliases: [P-Reinforce-AUTO-353103]
aliases: [Frontend Component Structure, Component Organization]
duplicate_of: none
source_trust_level: A
confidence_score: 0.9
tags: [auto-reinforced]
verification_status: applied
tags: [frontend, react, architecture, component-design]
raw_sources: []
last_reinforced: 2026-04-20
github_commit: "[P-Reinforce] Continuous Worker - 프론트엔드 컴포넌트 구조화"
inferred_by: Claude Opus 4.7 (auto-normalize 2026-05-08)
last_reinforced: 2026-05-10
github_commit: pending
tech_stack:
language: unspecified
framework: unspecified
language: typescript
framework: react-19/next-15
---
# [[프론트엔드 컴포넌트 구조화|프론트엔드 컴포넌트 구조화]]
# 프론트엔드 컴포넌트 구조화
## 📌 한 줄 통찰 (The Karpathy Summary)
> 프론트엔드 컴포넌트 구조화는 웹 개발에서 복잡성을 줄이고 유지보수성을 높이기 위해 기능과 역할 단위로 코드를 분리하고 조직하는 방법론입니다 [1, 2]. 초기에는 HTML, CSS, [[JavaScript|JavaScript]]라는 언어적 역할에 따라 분리되었으나, 특정 기능과 UI 요소를 하나의 단위로 묶는 컴포넌트 기반 아키텍처로 진화했습니다 [3]. 프로젝트의 규모가 커짐에 따라 발생하는 컴포넌트 간의 높은 결합도를 해결하기 위해, 관심사의 분리(SoC) 원칙을 다시 적용하여 [[Feature-Sliced Design|Feature-Sliced Design]](FSD)과 같이 기능 중심으로 구조를 세분화하는 방향으로 발전하고 있습니다 [2, 4].
## 한 줄
> **"매 component 의 size, scope, composition 의 systematic decomposition"**. 매 atomic design (atom→molecule→organism), feature-based (colocation), compound component, headless UI 의 4-axis. 매 2026 의 default — feature-folder + headless primitives (Radix/Ark) + Server Components.
## 📖 구조화된 지식 (Synthesized Content)
- **컴포넌트 패러다임의 등장과 한계:** 프론트엔드의 개발은 본래 문서의 구조, 표현, 동작을 위해 각각 HTML, CSS, JS라는 수평적 계층으로 나뉘어 있었으나, 웹 프레임워크의 도입과 함께 기능 중심의 모듈화를 의미하는 수직적 '컴포넌트' 방식으로 변화했습니다 [1, 3, 5]. 하지만 프로젝트가 비대해짐에 따라 하나의 컴포넌트 안에 데이터 관리, 표현 로직, 비즈니스 로직이 집중되어 단일 책임 원칙을 위반하고, 'props drilling'으로 인한 컴포넌트 간의 결합도가 지나치게 높아지는 문제가 발생했습니다 [4, 6].
- **계층적 관심사로의 회귀:** 컴포넌트의 한계를 극복하기 위해 다시 계층적 분리가 도입되었습니다 [7]. UI 컴포넌트의 명확한 역할과 계층을 나누기 위한 [[Atomic Design Pattern|Atomic Design Pattern]]의 도입, CSS가 HTML의 구조를 단방향으로 따라가게 만드는 의존성 해결, 그리고 화면(View)과 데이터 로직을 분리하여 단방향 데이터 흐름을 만드는 상태 관리(State [[Management|Management]]) 기법이 적용되었습니다 [8-10].
- **폴더 구조의 진화와 FSD 아키텍처:** 전통적인 폴더 구조는 역할(api, components, pages 등)을 중심으로 분리되었으나, 대규모 프로젝트에서는 기능 단위로 코드가 흩어지게 되어 파악이 어렵습니다 [11, 12]. 이에 따라 기능을 기준으로 필요한 모든 파일을 한 폴더에 모아 관리하는 Feature-Sliced Design(FSD) 아키텍처가 대안으로 등장했습니다 [2]. 이를 통해 기능 간의 결합도를 줄이고 독립적인 관리가 가능해집니다 [13].
- **올바른 컴포넌트 분리 원칙:** 프론트엔드 구조화에서 가장 흔한 실수는 겉모양이 비슷하다는 이유로 완전히 다른 도메인 데이터를 다루는 컴포넌트들을 하나로 묶어 재사용하려는 것입니다 [14]. 화면을 다루는 뷰 컴포넌트와 비즈니스 로직을 다루는 도메인 컴포넌트는 명확히 분리해야 하며, 만약 같은 화면 컴포넌트를 여러 도메인에서 공유해야 한다면 데이터를 변환하는 어댑터를 활용해 도메인별 데이터 규격을 화면 컴포넌트가 받아들일 수 있는 형태로 맞추어 전달하는 구조를 취해야 합니다 [15, 16].
## 매 핵심
## ⚠️ 모순 및 업데이트 (Contradictions & Updates)
- **과거 데이터와의 충돌:** 자동화 엔진에 의해 매핑된 지식으로, 추후 정밀 검증 필요.
- **정책 변화:** Design & Experience 분야의 자동 자산화 수행.
### 매 4 가지 axis
1. **Size**: atom · molecule · organism · template · page (Atomic Design).
2. **Scope**: feature-local vs shared / design system.
3. **Composition**: leaf vs container vs compound vs headless.
4. **Boundary**: Server Component vs Client Component (RSC).
## 🔗 지식 연결 (Graph)
- **Related Topics:** 관심사의 분리, [[Feature-Sliced Design|Feature-Sliced Design]], 단일 책임 원칙 (SRP), [[Atomic Design Pattern|Atomic Design Pattern]]
- **Projects/Contexts:** [[대규모 프론트엔드 웹 프로젝트 폴더 구조화|대규모 프론트엔드 웹 프로젝트 폴더 구조화]], [[컴포넌트 기반 웹 프레임워크 아키텍처 설계|컴포넌트 기반 웹 프레임워크 아키텍처 설계]]
- **Contradictions/Notes:** 초기 웹 개발은 HTML, CSS, JS라는 역할 중심의 계층 구조로 이루어졌으나, 컴포넌트 패러다임의 등장으로 기능 중심의 융합 구조로 변하였습니다 [1, 3]. 하지만 컴포넌트 비대화와 결합도 증가라는 복잡성 문제가 다시 발생함에 따라, 현대에는 컴포넌트 내외부를 다시 세분화된 역할과 기능(Feature) 단위로 분리하는 FSD 아키텍처 구조로 나아가는 진화 흐름을 보입니다 [2, 4, 7].
### 매 file/folder strategy
- **Co-location**: `components/Button/{index.tsx, Button.css, Button.test.tsx, Button.stories.tsx}`.
- **Feature folder**: `features/checkout/{components, hooks, api, types}` — feature 의 self-contained.
- **Shared design system**: `packages/ui` — monorepo + workspace.
---
*Last updated: 2026-04-18*
### 매 응용
1. Component library / design system 구축.
2. Large app 의 modular feature decomposition.
3. Server Components 의 server/client boundary 결정.
---
## 💻 패턴
## 🤖 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
### 1. Atomic Design folder
```
src/components/
atoms/ Button, Input, Icon
molecules/ SearchBar, FormField
organisms/ Header, ProductCard
templates/ CheckoutLayout
```
## 🤔 의사결정 기준 (Decision Criteria)
### 2. Feature-based folder (recommended 2026)
```
src/features/checkout/
components/CheckoutForm.tsx
hooks/useCheckout.ts
api/createOrder.ts
schemas/order.ts
index.ts // public API
```
**선택 A를 써야 할 때:**
- *(TODO)*
### 3. Compound component
```tsx
function Tabs({ children, defaultValue }: Props) {
const [value, setValue] = useState(defaultValue);
return <TabsContext.Provider value={{ value, setValue }}>{children}</TabsContext.Provider>;
}
Tabs.List = TabsList;
Tabs.Trigger = TabsTrigger;
Tabs.Content = TabsContent;
**선택 B를 써야 할 때:**
- *(TODO)*
// Usage:
<Tabs defaultValue="a">
<Tabs.List><Tabs.Trigger value="a">A</Tabs.Trigger></Tabs.List>
<Tabs.Content value="a">...</Tabs.Content>
</Tabs>
```
**기본값:**
> *(TODO)*
### 4. Headless component (Radix-style)
```tsx
function useDisclosure() {
const [open, setOpen] = useState(false);
return { open, toggle: () => setOpen(o => !o), close: () => setOpen(false) };
}
## ❌ 안티패턴 (Anti-Patterns)
// Consumer styles freely
function MyDialog() {
const d = useDisclosure();
return <div className="my-styles">{d.open && '...'}</div>;
}
```
- **[안티패턴]:** *(TODO: 무엇을 하면 안 되는가 + 이유 + 대신 무엇을)*
### 5. Server / Client boundary (Next.js 15)
```tsx
// app/products/page.tsx (Server Component — default)
import { ProductList } from './ProductList';
import { db } from '@/db';
export default async function Page() {
const products = await db.product.findMany();
return <ProductList products={products} />;
}
// app/products/AddToCart.tsx
'use client';
export function AddToCart({ id }: { id: string }) {
return <button onClick={() => addToCart(id)}>Add</button>;
}
```
### 6. Polymorphic component (`as` prop)
```tsx
type BoxProps<T extends React.ElementType> = {
as?: T;
} & React.ComponentPropsWithoutRef<T>;
function Box<T extends React.ElementType = 'div'>({ as, ...rest }: BoxProps<T>) {
const Tag = as || 'div';
return <Tag {...rest} />;
}
<Box as="a" href="/x">link</Box>;
```
### 7. Container / Presentational split (when useful)
```tsx
// Container — data + logic
function UserListContainer() {
const { data } = useUsers();
return <UserListView users={data} />;
}
// Presentational — pure UI
function UserListView({ users }: { users: User[] }) {
return <ul>{users.map(u => <li key={u.id}>{u.name}</li>)}</ul>;
}
```
### 8. Public API barrel (`index.ts`)
```typescript
// features/checkout/index.ts
export { CheckoutForm } from './components/CheckoutForm';
export { useCheckout } from './hooks/useCheckout';
export type { Order } from './schemas/order';
// 매 internal 은 export X — encapsulation.
```
## 매 결정 기준
| 상황 | Approach |
|---|---|
| Design system | Atomic + headless (Radix/Ark) |
| Product feature | Feature folder + co-location |
| Multi-trigger UI (Tabs, Menu) | Compound component |
| Style flexibility | Headless + custom CSS |
| Next.js 15 app | Server-default, Client only when needed |
| Reusable variant via tag | Polymorphic `as` |
**기본값**: 매 feature folder + 매 headless primitives (Radix/Ark) + 매 Server Components default.
## 🔗 Graph
- 부모: [[Component-Based Architecture]] · [[Frontend Architecture]]
- 변형: [[Atomic Design]] · [[Compound Components]] · [[Headless UI]] · [[Server Components]]
- 응용: [[Design System]] · [[Next.js App Router]] · [[Monorepo]]
- Adjacent: [[Custom Hooks]] · [[Render Props]] · [[Polymorphic Components]]
## 🤖 LLM 활용
**언제**: 매 large app 의 component decomposition 결정 시. 매 server/client boundary planning 시.
**언제 X**: 매 prototype / single-page demo — 매 over-structuring 의 X.
## ❌ 안티패턴
- **God component**: 매 1000-line component — 매 split.
- **Atomic Design 의 dogmatic 적용**: 매 feature 에는 feature folder 가 더 적합.
- **'use client' 남발**: 매 root 에 client 선언 — 매 RSC benefit 상실.
- **Container/Presentational 강요**: 매 hooks 시대에는 obsolete pattern.
- **Barrel re-export 의 deep nesting**: 매 bundler tree-shaking 방해.
## 🧪 검증 / 중복
- Verified (React docs, Next.js 15 docs, Radix UI / Ark UI patterns).
- 신뢰도 A.
## 🕓 Changelog
| 날짜 | 변경 |
|---|---|
| 2026-05-08 | Phase 1 |
| 2026-05-10 | Manual cleanup — 4-axis decomposition + 8 patterns + RSC boundary |