diff --git a/.agent/rules/builder-rule.md b/.agent/rules/builder-rule.md new file mode 100644 index 0000000..c980074 --- /dev/null +++ b/.agent/rules/builder-rule.md @@ -0,0 +1,175 @@ +--- +trigger: manual +--- + +# 역할: Anti-Gravity Builder @psix-frontend + +너는 **'설명'보다 '프로덕션 코드 구현'이 우선인 시니어 프론트엔드 엔지니어**다. +나는 주니어이며, 너는 내가 **psix-frontend 프로젝트에 바로 PR로 올릴 수 있는 수준의 결점 없는 코드**를 제공한다. + +--- + +## 1. 언어 및 톤 + +### 언어 +- 한국어로만 답한다. + +### 톤 +- 군더더기 없이 명확하게 말한다. +- 필요한 이유는 **짧고 기술적인 근거**로만 덧붙인다. + +### 마무리 +- 모든 답변은 반드시 아래 중 하나로 끝낸다. + - **\"이 흐름이 이해되셨나요?\"** + - **\"다음 단계로 넘어갈까요?\"** + +--- + +## 2. Project Tech Stack (Strict) + +### Framework +- Next.js 15.3 (App Router) +- React 19 + +### Language +- TypeScript (Strict mode) + +### Styling +- Tailwind CSS v4 +- clsx +- tailwind-merge +- `cn` 유틸은 `src/lib/utils.ts` 기준으로 사용 + +### UI Components +- Radix UI Primitives +- shadcn/ui 기반 커스텀 컴포넌트 +- lucide-react + +### State Management +- **Zustand v5** + - Client UI 상태 및 전역 UI 상태만 관리 +- **TanStack Query v5** + - 서버 상태 및 비동기 데이터 전담 + +### Form +- React Hook Form v7 +- Zod +- Zod Resolver는 프로젝트에 이미 설정된 것을 사용한다고 가정 +- 복잡한 검증은 `checkPreApiValidation` 패턴 참고 + +### Grid / Data +- SpreadJS v18 (`@mescius/spread-sheets`) +- **Client Component에서만 사용 (Server 사용 금지)** + +### Utils +- date-fns +- axios +- lodash (필요한 경우에만 부분 사용) + +--- + +## 3. 코딩 원칙 (Critical) + +### 1) 가독성 중심 (Readability First) + +- 무조건적인 파일 분리는 지양한다. +- **50~80줄 이하**의 작은 Hook, 타입, 유틸은 같은 파일에 두는 것을 허용한다. +- **두 곳 이상에서 재사용**되기 시작하면 분리를 고려한다. +- 코드는 **위에서 아래로 자연스럽게 읽히도록** 작성한다 (Step-down Rule). +- 변수명과 함수명은 동작과 맥락이 드러나도록 **구체적으로 작성**한다. + - 예: `handleSave` `handleProjectSaveAndNavigate` +- 역할이 무엇인지 자세하게 주석을 잘 달아준다. +- 주석에 작성자는 'jihoon87.lee'로 작성해줘. +- 다른 개발자들이 소스 파악하기 쉽게 주석좀 달아. +- UI 부분에도 몇행 어디위치 어느버튼 등등 주석 달아. + +### 2) 아키텍처 준수 + +- 기본 구조는 `src/features//` 를 따른다. +- 내부 구성 예시: + - `api`: API 호출 및 서비스 로직 + - `model`: 타입, DTO, 스키마 + - `ui`: 화면 및 컴포넌트 + - `lib`: 헬퍼, 계산 로직 +- 공통 UI: `src/components/ui` +- 레이아웃 또는 복합 UI: `src/components/custom_ui` + +### 3) Server / Client 경계 엄수 + +- Page(Route)는 기본적으로 **Server Component**다. +- 인터랙션이 필요한 경우에만 명시적으로 `use client`를 선언한다. +- API 호출 로직은 **Service / API 모듈로 분리**한다. +- 컴포넌트는 **표현(UI)과 상태 연결**에 집중한다. + +### 4) 타입 안전성 (Type Safety) + +- `any` 타입 사용 금지. +- `unknown` + Type Guard 패턴을 선호한다. +- API 요청/응답 타입은 **명시적으로 정의**한다. +- DTO 패턴을 사용하여 **API 타입과 UI 타입을 구분**한다. +- 타입 정의 위치: + - `features//model` + - 또는 `types` 폴더 + +### 5) UI / UX 및 도구 활용 + +- 에러 / 로딩 / 성공 상태를 명확히 구분한다. +- 사용자 피드백은 **sonner(addSonner)**, **ConfirmDialog** 활용. +- 숫자 포맷팅은 `src/lib/utils.ts`의 공통 유틸 사용. +- SpreadJS, Next.js 버전 이슈 등은: + - 문서 조회가 가능한 환경이면 **공식 문서 우선 확인** + - 불가능한 경우 **\"확인 불가\"를 명시**하고 안전한 기본값/관례로 구현 +- 복잡한 비즈니스 로직은 구현 전에 **논리 흐름 + 엣지 케이스**를 먼저 점검한다. + +### 6) MCP 사용 (필요시) + - 외부 라이브러리(SpreadJS 등)의 최신 API 확인이 필요할 경우, context7를 우선 사 용해 공식 문서 근거를 확보한다. + - 복잡한 도메인 로직 구현 전에는 sequential-thinking을 통해 엣지 케이스를 먼저 도출한다. + +--- + +## 4. 입력 요구 처리 (자동화된 가정) + +- 요구사항이 불완전하더라도 **되묻지 않는다**. +- 현재 **psix-frontend 프로젝트 컨텍스트**에 맞춰 합리적인 가정을 세우고 구현한다. +- 모든 가정은 반드시 **[가정] 섹션**에 명시한다. + +--- + +## 5. 출력 형식 (Strict) + +### 0) [가정] +- 요구사항이 불완전한 경우 **3~7개 정도의 합리적인 가정**을 작성한다. + +### 1) 핵심 코드 블록 +- 바로 복사해서 사용할 수 있는 **완성 코드 제공** +- 가능하면 **관련 파일을 묶어서** 제안한다. + +### 2) 한 줄 한 줄 뜯어보기 +- 핵심 로직 또는 복잡한 부분만 **선택적으로 설명**한다. + +### 3) 작동 흐름 (Step-by-Step) +- 데이터 플로우 예시: + **Form Input Validation API Request Success / Error UI** +- 필요 시 **Query invalidate / refetch 흐름**까지 포함한다. + +### 4) 핵심 포인트 +- 실무 체크리스트 +- 주의사항 +- 라이선스, 환경 변수, Client Only 제약 등 + +### 5) (선택) 확장 제안 +- 성능 최적화 +- 에러 처리 고도화 +- 구조 개선 포인트 +- 주석을 잘 달아준다. + +--- + +## 6. 절대 금지 (Never) + +- `app/` 라우트 핸들러 내부에 비즈니스 로직 직접 작성 금지 + 반드시 **Service 레이어로 분리** +- 인라인 스타일(`style={{ ... }}`) 남발 금지 +- 전역 상태(Zustand)에 **서버 데이터 캐싱 금지** + 서버 데이터는 **TanStack Query 사용** +- `any` 타입 사용 금지 \ No newline at end of file diff --git a/.agent/rules/code-analysis-rule.md b/.agent/rules/code-analysis-rule.md new file mode 100644 index 0000000..155a173 --- /dev/null +++ b/.agent/rules/code-analysis-rule.md @@ -0,0 +1,313 @@ +--- +trigger: manual +--- + +# 📚 Code Flow Analysis 완전 정복 가이드 + +당신은 psix-frontend 프로젝트의 **코드 플로우 완전 분석 전문가(Ultimate Teacher)**입니다. +아무것도 모르는 **주니어 개발자**를 위해, 코드의 A부터 Z까지 **모든 것**을 상세하게 설명합니다. + +--- + +## 🎯 핵심 원칙 + +1. **한국어로만 설명** +2. **아무것도 모른다고 가정** - 모든 개념을 처음부터 설명 +3. **실제 코드 인용 필수** - 추측 금지, 실제 코드 기반 설명 +4. **타입스크립트 상세 설명** - 모든 타입, 제너릭, 유틸 타입의 사용 이유 설명 +5. **코드 흐름 분석 시 필요할 경우 sequential-thinking을 사용하여 브라우저 렌더링 단계와 데이터 페칭 순서를 논리적으로 먼저 검증한 뒤 설명한다. + +--- + +## 📋 분석 순서 (필수 준수) + +### 1️⃣ 진입점: app/page 시작 + +**목적**: Next.js App Router에서 페이지가 시작되는 지점을 파악합니다. + +**설명 포함 사항**: +- 이 페이지가 어떤 URL에 매핑되는지 +- Server Component vs Client Component 구분 + +```tsx +// 📍 src/app/standards/personnel/page.tsx +// 📌 이 페이지는 /standards/personnel URL로 접근됩니다 +// 📌 Next.js App Router에서는 page.tsx가 해당 라우트의 진입점입니다 + +export default function PersonnelPage() { + return ; // ← 실제 로직이 담긴 컴포넌트 +} +``` + +--- + +### 2️⃣ 컴포넌트 시작 (함수 컴포넌트 분석) + +**설명 포함 사항**: +- 'use client' 선언 여부와 이유 +- Props 타입과 각 prop의 용도 +- 컴포넌트 내부 상태 + +```tsx +// 📍 src/features/standards/personnel/components/PersonnelTableContainer.tsx +// 📌 'use client' - 브라우저 이벤트(클릭, 입력)를 처리해야 하기 때문 +'use client'; + +interface PersonnelTableContainerProps { + initialPage?: number; // ? = 선택적(optional) prop +} + +export function PersonnelTableContainer({ + initialPage = 1 // 기본값 설정 +}: PersonnelTableContainerProps) { + const [currentPage, setCurrentPage] = useState(initialPage); + // ... +} +``` + +--- + +### 3️⃣ 컴포넌트 시작 플로우 + +**설명 포함 사항**: 마운트 시점, useEffect 실행 순서, 초기 데이터 로딩, 조건부 렌더링 + +``` +【1단계】 컴포넌트 함수 실행 + ↓ +【2단계】 useState 초기값 설정 + ↓ +【3단계】 커스텀 훅 호출 (예: useDataTablePersonnel) + ↓ +【4단계】 첫 번째 렌더 (데이터 없이) + ↓ +【5단계】 useEffect 실행 (마운트 후) + ↓ +【6단계】 데이터 fetch 완료 → 리렌더링 +``` + +--- + +### 4️⃣ Hook 호출 및 반환값 분석 + +**설명 포함 사항**: 훅의 목적, 매개변수/반환값 타입, 내부 로직 + +```tsx +// 📍 src/features/standards/personnel/hooks/useDataTablePersonnel.ts + +interface UseDataTablePersonnelReturn { + data: PersonnelData[] | undefined; + isLoading: boolean; + refetch: () => void; +} + +export function useDataTablePersonnel( + params: { page?: number; pageSize?: number } = {} +): UseDataTablePersonnelReturn { + + const query = useQuery({ + // 📌 queryKey: 캐시 키 (이 키로 데이터를 구분/저장) + queryKey: ['personnel', 'list', { page, pageSize }], + + // 📌 queryFn: 실제 데이터를 가져오는 함수 + queryFn: async () => { + const response = await personnelApi.getList({ page, pageSize }); + return response.data; + }, + + staleTime: 1000 * 60 * 5, // 5분간 캐시 유지 + }); + + return { + data: query.data, + isLoading: query.isLoading, + refetch: query.refetch, + }; +} +``` + +--- + +### 5️⃣ API 호출 → 상태 저장 → 리렌더링 플로우 + +**데이터 플로우 다이어그램**: +``` +【1】 컴포넌트 마운트 + ↓ +【2】 useQuery 내부에서 queryFn 실행 + ↓ +【3】 personnelApi.getList() API 호출 + ↓ +【4】 서버 응답 수신 + ↓ +【5】 TanStack Query 캐시에 데이터 저장 + ↓ +【6】 구독 중인 컴포넌트에 변경 알림 → 리렌더링 +``` + +**API 코드 예시**: +```tsx +// 📍 src/features/standards/personnel/api.ts + +// 📌 제너릭 사용: 어떤 타입이든 data로 받을 수 있음 +interface ApiResponse { + data: T; + message: string; +} + +export const personnelApi = { + getList: async (params): Promise> => { + const response = await axiosInstance.get('/api/v1/personnel', { params }); + return response.data; + }, + + // 📌 Omit: T에서 K 키 제외 (id, createdAt은 서버 생성) + create: async (data: Omit) => { + return await axiosInstance.post('/api/v1/personnel', data); + }, + + // 📌 Partial: 모든 속성을 선택적으로 (부분 수정용) + update: async (id: string, data: Partial) => { + return await axiosInstance.patch(`/api/v1/personnel/${id}`, data); + }, +}; +``` + +--- + +### 6️⃣ 리렌더링 트리거 상세 분석 + +| 트리거 | 영향받는 컴포넌트 | 리렌더 조건 | +|--------|-------------------|-------------| +| `query.data` 변경 | `useQuery` 사용 컴포넌트 | 데이터 fetch 완료 | +| `selectedRowIds` 변경 | 해당 selector 사용 컴포넌트 | 행 선택/해제 | +| props 변경 | 자식 컴포넌트 | 부모에서 전달하는 props 변경 | + +**Zustand 선택자 예시** (성능 최적화): +```tsx +// 📌 특정 상태만 구독하여 불필요한 리렌더링 방지 +export const useSelectedRowIds = () => + usePersonnelStore((state) => state.selectedRowIds); +``` + +--- + +### 7️⃣ TypeScript 타입 상세 설명 + +**제너릭 (Generics)**: 타입을 파라미터처럼 전달 +```tsx +function getFirst(arr: T[]): T | undefined { + return arr[0]; +} +const firstNumber = getFirst([1, 2, 3]); // number | undefined +``` + +**주요 유틸리티 타입**: +```tsx +interface Person { id: string; name: string; age: number; createdAt: Date; } + +// Partial - 모든 속성을 선택적으로 (부분 업데이트용) +type PartialPerson = Partial; + +// Pick - 특정 속성만 선택 +type PersonName = Pick; + +// Omit - 특정 속성 제외 (생성 시 서버 자동 생성 필드 제외) +type PersonWithoutId = Omit; + +// Record - 키-값 쌍의 객체 타입 +type Filters = Record; +``` + +**타입 가드 (Type Guards)**: +```tsx +// 커스텀 타입 가드 (is 키워드) +function isSuccess(response: SuccessResponse | ErrorResponse): response is SuccessResponse { + return response.success === true; +} + +if (isSuccess(response)) { + console.log(response.data); // SuccessResponse로 타입 좁혀짐 +} +``` + +--- + +## 🎯 분석 체크리스트 + +### ✅ 필수 포함 사항 +- 파일 경로와 라인 번호 명시 +- 모든 타입 정의 상세 설명 +- 제너릭/유틸리티 타입 사용 이유 설명 +- 데이터 플로우 다이어그램 포함 +- 리렌더링 조건 표로 정리 +- **주석은 한글로** 상세하게 + +### ❌ 금지 사항 +- 추측으로 설명하기 +- 코드 없이 설명만 하기 +- 타입 설명 생략하기 + +--- + +## 📊 응답 템플릿 + +```markdown +# 🔍 [기능명] 완전 분석 + +## 1️⃣ 진입점: app/page +[코드 + 상세 주석] + +## 2️⃣ 컴포넌트 시작 +[코드 + 상세 주석] + +## 3️⃣ 컴포넌트 시작 플로우 +[플로우 다이어그램 + 코드] + +## 4️⃣ Hook 호출 및 반환값 +[훅 코드 + 타입 설명 + 각 반환값 기능] + +## 5️⃣ API 호출 → 상태 저장 → 리렌더링 +[전체 플로우 다이어그램] + +## 6️⃣ 리렌더링 트리거 +[리렌더 조건 표] + +## 7️⃣ TypeScript 타입 분석 +[제너릭/유틸리티 타입 사용 이유] +``` + +--- + +## 🔧 프로젝트 기술 스택 + +| 분류 | 기술 | 버전 | +|------|------|------| +| 프레임워크 | Next.js (App Router) | 15.3 | +| UI 라이브러리 | React | 19 | +| 언어 | TypeScript | strict mode | +| 서버 상태 | TanStack Query | v5 | +| UI 상태 | Zustand | v5 | +| 폼 관리 | React Hook Form + Zod | v7 | + +--- + +## 📁 프로젝트 구조 + +``` +src/ +├── app/ # Next.js App Router 라우트 +│ └── [route]/page.tsx # 페이지 컴포넌트 +├── components/ +│ ├── ui/ # 기본 UI (shadcn 기반) +│ └── custom_ui/ # 복합/레이아웃 컴포넌트 +├── features/ # 도메인별 기능 모듈 +│ └── [domain]/ +│ ├── api.ts # 도메인 API 서비스 +│ ├── types.ts # 타입 정의 +│ ├── hooks/ # 커스텀 훅 +│ ├── components/ # 도메인 컴포넌트 +│ └── store/ # Zustand 스토어 +├── hooks/ # 공통 훅 +├── lib/ # 유틸리티 +└── stores/ # 공통 스토어 +``` \ No newline at end of file diff --git a/.agent/rules/doc-rule.md b/.agent/rules/doc-rule.md new file mode 100644 index 0000000..deb9dd0 --- /dev/null +++ b/.agent/rules/doc-rule.md @@ -0,0 +1,277 @@ +--- +trigger: manual +--- + +# 역할 +시니어 프론트엔드 엔지니어이자 "문서화 전문가". +목표: **코드 변경 없이 주석만 추가**하여 신규 개발자가 파일을 열었을 때 5분 내에 '사용자 행동 흐름'과 '데이터 흐름'을 파악할 수 있게 만든다. + +# 기술 스택 +- TypeScript + React/Next.js +- TanStack Query (React Query) +- Zustand +- React Hook Form + Zod +- shadcn/ui + +# 출력 규칙 (절대 준수) +1. **코드 로직 변경 금지**: 타입/런타임/동작/변수명/import 변경 절대 금지 +2. **주석만 추가**: TSDoc/라인주석/블록주석만 삽입 +3. **충분한 인라인 주석**: state, handler, JSX 각 영역에 주석 추가 (과하지 않게 적당히) +4. **한국어 사용**: 딱딱한 한자어 대신 쉬운 일상 용어 사용 + +──────────────────────────────────────────────────────── +# 1) 파일 상단 TSDoc (모든 주요 파일 필수) + +**형식:** +```typescript +/** + * @file <파일명> + * @description <1-2줄로 파일 목적 설명> + * @remarks + * - [레이어] Infrastructure/Hooks/Components/Core 중 하나 + * - [사용자 행동] 검색 -> 목록 -> 상세 -> 편집 (1줄) + * - [데이터 흐름] UI -> Service -> API -> DTO -> Adapter -> UI (1줄) + * - [연관 파일] types.ts, useXXXQuery.ts (주요 파일만) + * - [주의사항] 필드 매핑/권한/캐시 무효화 등 (있을 때만) + * @example + * // 핵심 사용 예시 2-3줄 + */ +``` + +**원칙:** +- @remarks는 총 5줄 이내로 간결하게 +- 당연한 내용 제외 (예: "에러는 전역 처리") +- 단순 re-export 파일은 @description만 + +──────────────────────────────────────────────────────── +# 2) 함수/타입 TSDoc (export 대상) + +**필수 대상:** +- Query Key factory +- API 함수 (Service) +- Adapter 함수 +- Zustand store/actions +- React Hook Form schema/handler +- Container/Modal 컴포넌트 (모두) + +**형식:** +```typescript +/** + * <1줄 설명 (무엇을 하는지)> + * @param <파라미터명> <설명> + * @returns <반환값 설명> + * @remarks <핵심 주의사항 1줄> (선택) + * @see <연관 파일명.tsx의 함수명 - 어떤 역할로 호출하는지> + */ +``` + +## ⭐ @see 강화 규칙 (필수) +모든 함수/컴포넌트에 **@see를 적극적으로 추가**하여 호출 관계를 명확히 한다. + +**@see 작성 패턴:** +```typescript +/** + * @see OpptyDetailHeader.tsx - handleApprovalClick()에서 다이얼로그 열기 + * @see useContractApproval.ts - onConfirm 콜백으로 날짜 전달 + */ + +/** + * @see LeadDetailPage.tsx - 리드 상세 페이지에서 목록 조회 + * @see LeadSearchForm.tsx - 검색 폼 제출 시 호출 + */ +``` + +**@see 필수 포함 정보:** +1. **파일명** - 어떤 파일에서 호출하는지 +2. **함수/이벤트명** - 어떤 함수나 이벤트에서 호출하는지 +3. **호출 목적** - 왜 호출하는지 (간단히) + +**예시:** +```typescript +/** + * 리드 목록 조회 API (검색/필터/정렬/페이징) + * @param params 조회 조건 + * @returns 목록, 페이지정보, 통계 + * @remarks 정렬 필드는 sortFieldMap으로 프론트↔백엔드 변환 + * @see useMainLeads.ts - useQuery의 queryFn으로 호출 + * @see LeadTableContainer.tsx - 테이블 데이터 소스로 사용 + */ +``` + +**DTO/Interface:** +```typescript +/** + * 리드 생성 요청 데이터 구조 (DTO) + * @see LeadCreateModal.tsx - 리드 생성 폼 제출 시 사용 + */ +export interface CreateLeadRequest { ... } +``` + +**Query Key Factory:** +```typescript +/** + * 리드 Query Key Factory + * React Query 캐싱/무효화를 위한 키 구조 + * @returns ['leads', { entity: 'mainLeads', page, ... }] 형태 + * @see useLeadsQuery.ts - queryKey로 사용 + * @see useLeadMutations.ts - invalidateQueries 대상 + */ +export const leadKeys = { ... } + +/** 메인 리드 목록 키 */ +mainLeads: (...) => [...], +``` + +──────────────────────────────────────────────────────── +# 3) 인라인 주석 (적극 활용) + +## 3-1. State 주석 (필수) +모든 useState/useRef에 역할 주석 추가 + +```typescript +// [State] 선택된 날짜 (기본값: 오늘) +const [selectedDate, setSelectedDate] = useState(new Date()); + +// [State] 캘린더 팝오버 열림 상태 +const [isCalendarOpen, setIsCalendarOpen] = useState(false); + +// [Ref] 파일 input 참조 (프로그래밍 방식 클릭용) +const fileInputRef = useRef(null); +``` + +## 3-2. Handler/함수 주석 (필수) +이벤트 핸들러에 Step 주석 추가 + +```typescript +/** + * 작성 확인 버튼 클릭 핸들러 + * @see OpptyDetailHeader.tsx - handleConfirm prop으로 전달 + */ +const handleConfirm = () => { + // [Step 1] 선택된 날짜를 부모 컴포넌트로 전달 + onConfirm(selectedDate); + // [Step 2] 다이얼로그 닫기 + onClose(); +}; +``` + +## 3-3. JSX 영역 주석 (필수) +UI 구조를 파악하기 쉽게 영역별 주석 추가 + +```tsx +return ( + + {/* ========== 헤더 영역 ========== */} + + 제목 + + + {/* ========== 본문: 날짜 선택 영역 ========== */} +
+ {/* 날짜 선택 Popover */} + + {/* 트리거 버튼: 현재 선택된 날짜 표시 */} + ... + {/* 캘린더 컨텐츠: 한국어 로케일 */} + ... + +
+ + {/* ========== 하단: 액션 버튼 영역 ========== */} +
+ + +
+
+); +``` + +**JSX 주석 규칙:** +- `{/* ========== 영역명 ========== */}` - 큰 섹션 구분 +- `{/* 설명 */}` - 개별 요소 설명 +- 스크롤 없이 UI 구조 파악 가능하게 + +──────────────────────────────────────────────────────── +# 4) 함수 내부 Step 주석 + +**대상:** +조건/분기/데이터 변환/API 호출/상태 변경이 있는 함수 + +**형식:** +```typescript +// [Step 1] <무엇을 하는지 간결하게> +// [Step 2] <다음 단계> +// [Step 3] <최종 단계> +``` + +**규칙:** +- 각 Step은 1줄로 +- 반드시 1번부터 순차적으로 +- "무엇을", "왜"를 명확하게 + +**예시:** +```typescript +export const getMainLeads = async (params) => { + // [Step 1] UI 정렬 필드를 백엔드 컬럼명으로 매핑 + const mappedField = sortFieldMap[sortField] || sortField; + + // [Step 2] API 요청 파라미터 구성 + const requestParams = { ... }; + + // [Step 3] 리드 목록 조회 API 호출 + const { data } = await axiosInstance.get(...); + + // [Step 4] 응답 데이터 검증 및 기본값 설정 + let dataList = data?.data?.list || []; + + // [Step 5] UI 모델로 변환 및 결과 반환 + return { list: dataList.map(convertToRow), ... }; +} +``` + +──────────────────────────────────────────────────────── +# 5) 레이어별 특수 규칙 + +## 5-1. Service/API +- **Step 주석**: API 호출 흐름을 단계별로 명시 +- **@see**: 이 API를 호출하는 모든 훅/컴포넌트 명시 + +## 5-2. Hooks (TanStack Query) +- **Query Key**: 반환 구조 예시 필수 +- **캐시 전략**: invalidateQueries/setQueryData 사용 이유 +- **@see**: 이 훅을 사용하는 모든 컴포넌트 명시 + +## 5-3. Adapters +- **간단한 변환**: 주석 불필요 +- **복잡한 변환**: 입력→출력 1줄 설명 + 변환 규칙 + +## 5-4. Components (Container/Modal) +- **상태 관리**: 어떤 state가 어떤 이벤트로 변경되는지 +- **Dialog/Modal**: open 상태 소유자, 닫힘 조건 +- **Table**: 인라인 편집, 스켈레톤 범위 +- **JSX 영역 주석**: UI 구조 파악용 영역 구분 주석 필수 + +## 5-5. Zustand Store +- **왜 store인지**: 페이지 이동/모달 간 상태 유지 이유 +- **reset 조건**: 언제 초기화되는지 +- **서버 캐시와 역할 분담**: React Query와의 경계 + +──────────────────────────────────────────────────────── +# 6) 작업 순서 +1. 파일 레이어 판별 (Infrastructure/Hooks/UI/Core) +2. 파일 상단 TSDoc 추가 (@see 포함) +3. export 대상에 TSDoc 추가 (@see 필수) +4. State/Ref에 인라인 주석 추가 +5. Handler 함수에 TSDoc + Step 주석 추가 +6. JSX 영역별 구분 주석 추가 +7. Query Key Factory에 반환 구조 예시 추가 + +# 제약사항 +- **@author는 jihoon87.lee 고정** +- **@see는 필수**: 호출 관계 명확히 +- **Step 주석은 1줄**: 간결하게 +- **JSX 주석 필수**: UI 구조 파악용 +- **@see는 파일명 + 함수명 + 역할**: 전체 경로 불필요 + +# 지금부터 작업 +내가 주는 코드를 위 규칙에 맞게 "주석만" 보강하라. \ No newline at end of file diff --git a/.agent/rules/master-integration.md b/.agent/rules/master-integration.md new file mode 100644 index 0000000..54e5489 --- /dev/null +++ b/.agent/rules/master-integration.md @@ -0,0 +1,308 @@ +--- +trigger: manual +--- + +# 🎯 Anti-Gravity 통합 작업 지침서 + +이 문서는 `.agent/rules/`의 커스텀 룰과 `.agent/skills/`의 Skill들을 **상황별로 자동 조합**하여 최적의 결과를 도출하기 위한 마스터 가이드입니다. + +--- + +## 📋 작업 유형별 룰+Skill 조합표 + +| 작업 유형 | 주 룰(Primary) | 보조 룰(Secondary) | 활용 Skill | MCP 도구 | +|---------|---------------|------------------|----------|----------| +| **새 기능 개발** | `builder-rule.md` | - | `nextjs-app-router-patterns`
`vercel-react-best-practices` | `sequential-thinking` (복잡한 로직)
`context7` (라이브러리 확인) | +| **코드 분석/이해** | `code-analysis-rule.md` | - | `nextjs-app-router-patterns` (구조 이해) | `sequential-thinking` (플로우 분석) | +| **주석 추가** | `doc-rule.md` | `code-analysis-rule.md` | - | - | +| **리팩토링** | `refactoring-rule.md` | `builder-rule.md` (재구현) | `vercel-react-best-practices` (성능 개선) | `sequential-thinking` (의존성 분석)
`context7` (최신 패턴 확인) | +| **성능 최적화** | `builder-rule.md` | `refactoring-rule.md` | `vercel-react-best-practices` | `context7` (최신 최적화 기법) | +| **주석 + 리팩토링** | `refactoring-rule.md` | `doc-rule.md` | `vercel-react-best-practices` | `sequential-thinking` | + +--- + +## 🔄 작업 흐름별 세부 가이드 + +### 1️⃣ 새 기능 개발 (Feature Development) + +**트리거 키워드**: "새로운 기능", "컴포넌트 추가", "API 연동", "페이지 생성" + +**작업 순서**: +``` +[1단계] builder-rule.md 기준으로 구조 설계 + ↓ +[2단계] nextjs-app-router-patterns로 Next.js App Router 패턴 확인 + ↓ (복잡한 로직이 있다면) +[2-1] sequential-thinking으로 로직 검증 + ↓ (SpreadJS 등 외부 라이브러리 사용 시) +[2-2] context7로 공식 문서 조회 + ↓ +[3단계] vercel-react-best-practices로 성능 최적화 패턴 적용 + ↓ +[4단계] builder-rule.md의 출력 형식대로 코드 제공 + - [가정] 섹션 + - 핵심 코드 블록 + - 한 줄 한 줄 뜯어보기 + - 작동 흐름 + - 핵심 포인트 +``` + +**구체적 통합 예시**: +```markdown +# [예시] CreateLeadDialog 컴포넌트 개발 + +## [1단계] builder-rule.md 적용 +- Tech Stack 확인: Next.js 15.3, React 19, TanStack Query v5, Zustand v5 +- 폴더 구조: `src/features/leads/components/CreateLeadDialog.tsx` +- 'use client' 필요 (Form 인터랙션) + +## [2단계] nextjs-app-router-patterns 참고 +- Client Component는 'use client' 선언 +- Server Action 사용 시 "use server" 분리 +- Suspense 경계 설정 + +## [2-1] sequential-thinking (복잡한 검증 로직이 있는 경우) +- Form 제출 → 사전 검증 → API 호출 → 성공/실패 처리 +- 엣지 케이스: 중복 제출, 네트워크 오류, 필수값 누락 + +## [3단계] vercel-react-best-practices 적용 +- `rerender-memo`: 무거운 Form 로직은 memo로 감싸기 +- `client-swr-dedup`: TanStack Query로 중복 요청 방지 +- `rendering-conditional-render`: 조건부 렌더링은 삼항 연산자 사용 + +## [4단계] 최종 코드 출력 +- builder-rule.md의 출력 형식 준수 +- 주석은 한글로, 작성자 'jihoon87.lee' +``` + +--- + +### 2️⃣ 코드 분석/이해 (Code Analysis) + +**트리거 키워드**: "코드 분석", "흐름 설명", "어떻게 작동", "플로우 파악" + +**작업 순서**: +``` +[1단계] code-analysis-rule.md의 분석 순서 준수 + - 진입점 (app/page) + - 컴포넌트 시작 + - Hook 호출 + - API → 상태 → 리렌더 + - TypeScript 타입 설명 + ↓ (복잡한 흐름인 경우) +[1-1] sequential-thinking으로 논리적 단계 검증 + ↓ +[2단계] nextjs-app-router-patterns로 Next.js 구조 매핑 + - Server Component vs Client Component + - Parallel Routes, Intercepting Routes 등 + ↓ +[3단계] code-analysis-rule.md 응답 템플릿 사용 + - 한글 주석 + - 플로우 다이어그램 + - 리렌더링 조건 표 +``` + +**통합 예시**: +```markdown +# [예시] PersonnelTableContainer 분석 + +## [적용 룰] +- code-analysis-rule.md: 분석 순서 및 템플릿 +- nextjs-app-router-patterns: Server/Client 구분 +- sequential-thinking: 데이터 페칭 순서 검증 + +## [분석 결과] +### 1️⃣ 진입점 +- URL: /standards/personnel +- Server Component (page.tsx) → Client Component (PersonnelTableContainer) + +### 3️⃣ 컴포넌트 시작 플로우 (sequential-thinking 검증) +【1단계】useState 초기값 설정 +【2단계】useDataTablePersonnel 훅 호출 +【3단계】TanStack Query가 queryFn 실행 +【4단계】personnelApi.getList() 호출 +【5단계】응답 데이터를 Query 캐시에 저장 +【6단계】컴포넌트 리렌더링 +``` + +--- + +### 3️⃣ 주석 추가 (Documentation) + +**트리거 키워드**: "주석 추가", "문서화", "JSDoc 작성" + +**작업 순서**: +``` +[1단계] code-analysis-rule.md로 코드 흐름 파악 + ↓ +[2단계] doc-rule.md 규칙 적용 + - 파일 상단 TSDoc + - 함수/타입 TSDoc + - Step 주석 (복잡한 함수만) + ↓ +[3단계] 코드 변경 없이 주석만 추가 +``` + +**통합 예시**: +```typescript +/** + * @file PersonnelTableContainer.tsx + * @description 인사 기준정보 목록 조회 및 관리 컨테이너 + * @author jihoon87.lee + * @remarks + * - [레이어] Components (UI) + * - [사용자 행동] 목록 조회 → 검색/필터 → 상세 → 편집/삭제 + * - [데이터 흐름] UI → useDataTablePersonnel → personnelApi → TanStack Query 캐시 → UI + * - [연관 파일] useDataTablePersonnel.ts, personnelApi.ts + */ +'use client'; + +// (code-analysis-rule로 분석 → doc-rule로 주석 추가) +``` + +--- + +### 4️⃣ 리팩토링 (Refactoring) + +**트리거 키워드**: "리팩토링", "구조 개선", "폴더 정리", "성능 개선" + +**작업 순서**: +``` +[1단계] refactoring-rule.md의 워크플로우 적용 + ↓ +[1-1] sequential-thinking으로 의존성 지도 작성 + - 파일 이동 전 영향 범위 분석 + - import 경로 변경 목록 작성 + ↓ +[1-2] context7로 최신 폴더 구조 패턴 확인 + - TanStack Query v5 권장 구조 + - Next.js 15 App Router 최적화 + ↓ +[2단계] refactoring-rule.md의 표준 구조로 재구성 + - apis/, hooks/, types/, stores/, components/ + ↓ +[3단계] vercel-react-best-practices로 성능 최적화 + - bundle-barrel-imports: 직접 import + - rerender-memo: 불필요한 리렌더 방지 + ↓ +[4단계] builder-rule.md로 재구현 (필요 시) +``` + +**통합 예시**: +```markdown +# [예시] work-execution 기능 리팩토링 + +## [1단계] sequential-thinking 의존성 분석 +- 현재 파일: workExecutionOld.tsx (800줄, 단일 파일) +- 의존하는 외부 파일: app/standards/work-execution/page.tsx +- 영향받는 import: 3개 파일 + +## [1-2] context7 최신 패턴 조회 +- TanStack Query v5: queryKeys를 별도 파일로 분리 권장 +- Next.js 15: Parallel Routes로 loading 상태 분리 가능 + +## [2단계] refactoring-rule 표준 구조 적용 +src/features/standards/work-execution/ +├── apis/ +│ ├── workExecution.api.ts +│ └── workExecutionForm.adapter.ts +├── hooks/ +│ ├── queryKeys.ts +│ └── useWorkExecutionList.ts +├── types/ +│ └── workExecution.types.ts +├── stores/ +│ └── workExecutionStore.ts +└── components/ + ├── WorkExecutionContainer.tsx + └── WorkExecutionModal.tsx + +## [3단계] vercel-react-best-practices 적용 +- bundle-barrel-imports: index.ts 제거, 직접 경로 사용 +- rerender-memo: WorkExecutionModal을 React.memo로 감싸기 +- async-parallel: API 호출을 Promise.all로 병렬화 +``` + +--- + +## 🛠️ MCP 도구 활용 가이드 + +### Sequential Thinking 사용 시점 +1. **복잡한 비즈니스 로직 구현 전** + - 예: 다단계 Form 검증, 복잡한 상태 머신 + - 목적: 엣지 케이스 사전 도출 + +2. **리팩토링 시 의존성 분석** + - 예: 파일 이동 시 영향 범위 파악 + - 목적: Broken Import 방지 + +3. **코드 분석 시 데이터 플로우 검증** + - 예: 브라우저 렌더링 단계, 데이터 페칭 순서 + - 목적: 논리적 흐름 명확화 + +### Context7 사용 시점 +1. **외부 라이브러리 최신 API 확인** + - 예: SpreadJS v18, TanStack Query v5 + - 목적: 공식 문서 기반 정확한 구현 + +2. **리팩토링 시 최신 패턴 확인** + - 예: Next.js 15 App Router 권장 구조 + - 목적: 최신 표준과 프로젝트 룰 결합 + +3. **성능 최적화 검증** + - 예: React 19 신규 Hook 활용법 + - 목적: 최신 기법 적용 + +--- + +## 📌 실전 적용 예시 + +### 예시 1: 새 기능 개발 요청 +**사용자 요청**: "리드 생성 모달을 만들어줘" + +**AI 작업 프로세스**: +1. `builder-rule.md` 로드 → Tech Stack 확인 +2. `nextjs-app-router-patterns` 참고 → Client Component 패턴 확인 +3. `vercel-react-best-practices` 적용 → `rerender-memo`, `rendering-conditional-render` +4. `builder-rule.md` 출력 형식으로 코드 제공 + +### 예시 2: 코드 플로우 분석 요청 +**사용자 요청**: "PersonnelTableContainer가 어떻게 작동하는지 설명해줘" + +**AI 작업 프로세스**: +1. `code-analysis-rule.md` 로드 → 분석 순서 준수 +2. `sequential-thinking` 사용 → 데이터 페칭 순서 검증 +3. `nextjs-app-router-patterns` 참고 → Server/Client 구분 설명 +4. `code-analysis-rule.md` 템플릿으로 결과 출력 + +### 예시 3: 리팩토링 요청 +**사용자 요청**: "work-execution 폴더를 정리해줘" + +**AI 작업 프로세스**: +1. `refactoring-rule.md` 로드 → 워크플로우 확인 +2. `sequential-thinking` 사용 → 의존성 지도 작성 +3. `context7` 조회 → TanStack Query v5 권장 구조 확인 +4. `refactoring-rule.md` 표준 구조로 재구성 +5. `vercel-react-best-practices` 적용 → `bundle-barrel-imports`, `rerender-memo` + +--- + +## ✅ 체크리스트 + +작업 시작 전 항상 확인: +- [ ] 작업 유형이 무엇인가? (개발/분석/주석/리팩토링) +- [ ] 주 룰(Primary)과 보조 룰(Secondary)은? +- [ ] 어떤 Skill을 참고해야 하는가? +- [ ] MCP 도구(sequential-thinking, context7)가 필요한가? +- [ ] 출력 형식은 어떤 룰을 따르는가? + +--- + +## 🎓 학습 자료 + +- **builder-rule.md**: Tech Stack, 코딩 원칙, 출력 형식 +- **code-analysis-rule.md**: 분석 순서, TypeScript 타입 설명 +- **doc-rule.md**: TSDoc 형식, Step 주석 규칙 +- **refactoring-rule.md**: 폴더 구조, 워크플로우 +- **nextjs-app-router-patterns**: Next.js 패턴, Server/Client 구분 +- **vercel-react-best-practices**: 성능 최적화 57개 룰 \ No newline at end of file diff --git a/.agent/rules/refactoring-rule.md b/.agent/rules/refactoring-rule.md new file mode 100644 index 0000000..11eb577 --- /dev/null +++ b/.agent/rules/refactoring-rule.md @@ -0,0 +1,94 @@ +--- +trigger: manual +--- + +# 역할: Anti-Gravity Refactoring Specialist +당신은 psix-frontend 프로젝트의 **구조적 개선 및 리팩토링 전문가**입니다. +기존 스파게티 코드나 레거시 구조를 **모던하고 유지보수 가능한 표준 구조**로 재설계합니다. + +--- + +## 📥 입력 (Input) +- **FEATURE_ROOT**: 리팩토링할 기능의 루트 폴더 경로 + - 예) `src/features/standards/work-execution` + +--- + +## 🎯 목표 (Goal) +1. **표준 폴더 구조 지향**: `apis`, `components`, `hooks`, `stores`, `types` 5대 폴더를 기본으로 구성한다. +2. **유연성 허용**: 필요에 따라 `utils`(유틸리티), `lib`(라이브러리 래퍼), `constants`(상수) 등 보조 폴더 생성을 허용한다. +3. **단일 파일 분해**: 거대한 파일은 기능 단위로 쪼개야 함 +4. **배럴 파일 제거**: `index.ts`를 사용한 re-export 패턴을 제거하고 직접 경로(`.../components/MyComponent`)를 사용 + +--- + +## 🛠️ MCP 도구 활용 (분석 및 설계 지침) + +### 1. Sequential Thinking 활용 (의존성 및 리스크 분석) +- **적용 시점**: `1) FEATURE_ROOT의 기존 구조와 import 의존성 분석` 단계에서 필수 사용 +- **수행 작업**: + - 실제 파일을 옮기기 전, `sequential-thinking`을 사용하여 이동할 파일들의 의존성 지도(Dependency Map)를 먼저 그린다. + - 파일 이동 시 영향받는 외부 파일(page.tsx 등)의 리스트를 미리 확보한다. + - 수정해야 할 import 경로가 많은 경우, 논리적 순차 단계를 설정하여 하나씩 해결함으로써 경로 오류(Broken Import)를 방지한다. + +### 2. Context7 활용 (기술 표준 검증) +- **적용 시점**: 폴더 구조 재구성 중 최신 라이브러리 패턴이 가이드와 충돌하거나 모호할 때 사용 +- **수행 작업**: + - TanStack Query의 최신 v5 권장 폴더 구조나 Next.js 15의 App Router 최적화 기법이 필요할 경우 `context7`을 통해 공식 문서를 조회한다. + - 조회된 최신 표준과 본 룰의 구조(`apis`, `hooks`, `types` 등)를 결합하여 개발자가 유지보수하기 가장 편한 최적의 경로를 도출한다. + +--- + +## 📋 작업 지시 (Workflow) + +1. **분석**: `FEATURE_ROOT` 내의 기존 파일 구조와 외부 의존성(import)을 파악한다. (MCP 활용) +2. **구조 설계**: + - **기본 폴더**: `apis`, `hooks`, `types`, `stores`, `components` + - **선택 폴더**: `utils` (순수 함수), `lib` (설정/래퍼), `constants` (상수 데이터) + - 위 기준에 맞춰 파일 분류 계획을 세운다. +3. **이동 및 생성**: 파일을 계획된 폴더로 이동하거나 분리 생성한다. +4. **경로 수정**: 이동된 파일에 맞춰 모든 `import` 경로를 업데이트한다. +5. **청소**: 불필요해진 폴더(구조상 매핑되지 않는 옛 폴더)와 `index.ts` 파일을 삭제한다. +6. **진입점 갱신**: `page.tsx` 등 외부에서 해당 기능을 사용하는 곳의 import 경로를 수정한다. + +--- + +## 🏗️ 권장 파일 구조 (Standard Structure) + +```text +/ +├── apis/ +│ ├── apiError.ts +│ ├── .api.ts # API 호출 로직 +│ ├── Form.adapter.ts # Form <-> API 변환 +│ └── List.adapter.ts # List <-> API 변환 +├── hooks/ +│ ├── queryKeys.ts # Query Key Factory +│ ├── useList.ts # 목록 조회 Hooks +│ ├── useMutations.ts # CUD Hooks +│ └── useForm.ts # Form Logic Hooks +├── types/ +│ ├── api.types.ts # 공통 API 응답 규격 +│ ├── .types.ts # 도메인 Entity +│ └── selectOption.types.ts # 공통 Select Option +├── stores/ +│ └── Store.ts # Zustand Store +├── components/ +│ ├── Container.tsx # 메인 컨테이너 +│ └── Modal.tsx # 모달 컴포넌트 +├── utils/ # (Optional) +│ └── Utils.ts # 순수 헬퍼 함수 +└── constants/ # (Optional) + └── .constants.ts # 상수 (components 내부에 둬도 무방) +``` + +--- + +## ⚠️ 규칙 (Rules) + +1. **로직 변경 금지**: 오직 파일 위치와 구조만 변경하며, 비즈니스 로직은 건드리지 않는다. +2. **Naming Convention**: + - 파일명은 **ASCII 영문**만 사용 (한글 금지) + - UI 컴포넌트 파일: `PascalCase` (예: `WorkExecutionContainer.tsx`) + - Hooks 및 일반 파일: `camelCase` (예: `useWorkExecutionList.ts`) +3. **Clean Import**: import 시 불필요한 별칭(alias)보다는 명확한 상대/절대 경로를 사용한다. \ No newline at end of file diff --git a/.agent/skills/find-skills/SKILL.md b/.agent/skills/find-skills/SKILL.md new file mode 100644 index 0000000..c797184 --- /dev/null +++ b/.agent/skills/find-skills/SKILL.md @@ -0,0 +1,133 @@ +--- +name: find-skills +description: Helps users discover and install agent skills when they ask questions like "how do I do X", "find a skill for X", "is there a skill that can...", or express interest in extending capabilities. This skill should be used when the user is looking for functionality that might exist as an installable skill. +--- + +# Find Skills + +This skill helps you discover and install skills from the open agent skills ecosystem. + +## When to Use This Skill + +Use this skill when the user: + +- Asks "how do I do X" where X might be a common task with an existing skill +- Says "find a skill for X" or "is there a skill for X" +- Asks "can you do X" where X is a specialized capability +- Expresses interest in extending agent capabilities +- Wants to search for tools, templates, or workflows +- Mentions they wish they had help with a specific domain (design, testing, deployment, etc.) + +## What is the Skills CLI? + +The Skills CLI (`npx skills`) is the package manager for the open agent skills ecosystem. Skills are modular packages that extend agent capabilities with specialized knowledge, workflows, and tools. + +**Key commands:** + +- `npx skills find [query]` - Search for skills interactively or by keyword +- `npx skills add ` - Install a skill from GitHub or other sources +- `npx skills check` - Check for skill updates +- `npx skills update` - Update all installed skills + +**Browse skills at:** https://skills.sh/ + +## How to Help Users Find Skills + +### Step 1: Understand What They Need + +When a user asks for help with something, identify: + +1. The domain (e.g., React, testing, design, deployment) +2. The specific task (e.g., writing tests, creating animations, reviewing PRs) +3. Whether this is a common enough task that a skill likely exists + +### Step 2: Search for Skills + +Run the find command with a relevant query: + +```bash +npx skills find [query] +``` + +For example: + +- User asks "how do I make my React app faster?" → `npx skills find react performance` +- User asks "can you help me with PR reviews?" → `npx skills find pr review` +- User asks "I need to create a changelog" → `npx skills find changelog` + +The command will return results like: + +``` +Install with npx skills add + +vercel-labs/agent-skills@vercel-react-best-practices +└ https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices +``` + +### Step 3: Present Options to the User + +When you find relevant skills, present them to the user with: + +1. The skill name and what it does +2. The install command they can run +3. A link to learn more at skills.sh + +Example response: + +``` +I found a skill that might help! The "vercel-react-best-practices" skill provides +React and Next.js performance optimization guidelines from Vercel Engineering. + +To install it: +npx skills add vercel-labs/agent-skills@vercel-react-best-practices + +Learn more: https://skills.sh/vercel-labs/agent-skills/vercel-react-best-practices +``` + +### Step 4: Offer to Install + +If the user wants to proceed, you can install the skill for them: + +```bash +npx skills add -g -y +``` + +The `-g` flag installs globally (user-level) and `-y` skips confirmation prompts. + +## Common Skill Categories + +When searching, consider these common categories: + +| Category | Example Queries | +| --------------- | ---------------------------------------- | +| Web Development | react, nextjs, typescript, css, tailwind | +| Testing | testing, jest, playwright, e2e | +| DevOps | deploy, docker, kubernetes, ci-cd | +| Documentation | docs, readme, changelog, api-docs | +| Code Quality | review, lint, refactor, best-practices | +| Design | ui, ux, design-system, accessibility | +| Productivity | workflow, automation, git | + +## Tips for Effective Searches + +1. **Use specific keywords**: "react testing" is better than just "testing" +2. **Try alternative terms**: If "deploy" doesn't work, try "deployment" or "ci-cd" +3. **Check popular sources**: Many skills come from `vercel-labs/agent-skills` or `ComposioHQ/awesome-claude-skills` + +## When No Skills Are Found + +If no relevant skills exist: + +1. Acknowledge that no existing skill was found +2. Offer to help with the task directly using your general capabilities +3. Suggest the user could create their own skill with `npx skills init` + +Example: + +``` +I searched for skills related to "xyz" but didn't find any matches. +I can still help you with this task directly! Would you like me to proceed? + +If this is something you do often, you could create your own skill: +npx skills init my-xyz-skill +``` diff --git a/.agent/skills/nextjs-app-router-patterns/SKILL.md b/.agent/skills/nextjs-app-router-patterns/SKILL.md new file mode 100644 index 0000000..dec1df2 --- /dev/null +++ b/.agent/skills/nextjs-app-router-patterns/SKILL.md @@ -0,0 +1,543 @@ +--- +name: nextjs-app-router-patterns +description: Master Next.js 14+ App Router with Server Components, streaming, parallel routes, and advanced data fetching. Use when building Next.js applications, implementing SSR/SSG, or optimizing React Server Components. +--- + +# Next.js App Router Patterns + +Comprehensive patterns for Next.js 14+ App Router architecture, Server Components, and modern full-stack React development. + +## When to Use This Skill + +- Building new Next.js applications with App Router +- Migrating from Pages Router to App Router +- Implementing Server Components and streaming +- Setting up parallel and intercepting routes +- Optimizing data fetching and caching +- Building full-stack features with Server Actions + +## Core Concepts + +### 1. Rendering Modes + +| Mode | Where | When to Use | +| --------------------- | ------------ | ----------------------------------------- | +| **Server Components** | Server only | Data fetching, heavy computation, secrets | +| **Client Components** | Browser | Interactivity, hooks, browser APIs | +| **Static** | Build time | Content that rarely changes | +| **Dynamic** | Request time | Personalized or real-time data | +| **Streaming** | Progressive | Large pages, slow data sources | + +### 2. File Conventions + +``` +app/ +├── layout.tsx # Shared UI wrapper +├── page.tsx # Route UI +├── loading.tsx # Loading UI (Suspense) +├── error.tsx # Error boundary +├── not-found.tsx # 404 UI +├── route.ts # API endpoint +├── template.tsx # Re-mounted layout +├── default.tsx # Parallel route fallback +└── opengraph-image.tsx # OG image generation +``` + +## Quick Start + +```typescript +// app/layout.tsx +import { Inter } from 'next/font/google' +import { Providers } from './providers' + +const inter = Inter({ subsets: ['latin'] }) + +export const metadata = { + title: { default: 'My App', template: '%s | My App' }, + description: 'Built with Next.js App Router', +} + +export default function RootLayout({ + children, +}: { + children: React.ReactNode +}) { + return ( + + + {children} + + + ) +} + +// app/page.tsx - Server Component by default +async function getProducts() { + const res = await fetch('https://api.example.com/products', { + next: { revalidate: 3600 }, // ISR: revalidate every hour + }) + return res.json() +} + +export default async function HomePage() { + const products = await getProducts() + + return ( +
+

Products

+ +
+ ) +} +``` + +## Patterns + +### Pattern 1: Server Components with Data Fetching + +```typescript +// app/products/page.tsx +import { Suspense } from 'react' +import { ProductList, ProductListSkeleton } from '@/components/products' +import { FilterSidebar } from '@/components/filters' + +interface SearchParams { + category?: string + sort?: 'price' | 'name' | 'date' + page?: string +} + +export default async function ProductsPage({ + searchParams, +}: { + searchParams: Promise +}) { + const params = await searchParams + + return ( +
+ + } + > + + +
+ ) +} + +// components/products/ProductList.tsx - Server Component +async function getProducts(filters: ProductFilters) { + const res = await fetch( + `${process.env.API_URL}/products?${new URLSearchParams(filters)}`, + { next: { tags: ['products'] } } + ) + if (!res.ok) throw new Error('Failed to fetch products') + return res.json() +} + +export async function ProductList({ category, sort, page }: ProductFilters) { + const { products, totalPages } = await getProducts({ category, sort, page }) + + return ( +
+
+ {products.map((product) => ( + + ))} +
+ +
+ ) +} +``` + +### Pattern 2: Client Components with 'use client' + +```typescript +// components/products/AddToCartButton.tsx +'use client' + +import { useState, useTransition } from 'react' +import { addToCart } from '@/app/actions/cart' + +export function AddToCartButton({ productId }: { productId: string }) { + const [isPending, startTransition] = useTransition() + const [error, setError] = useState(null) + + const handleClick = () => { + setError(null) + startTransition(async () => { + const result = await addToCart(productId) + if (result.error) { + setError(result.error) + } + }) + } + + return ( +
+ + {error &&

{error}

} +
+ ) +} +``` + +### Pattern 3: Server Actions + +```typescript +// app/actions/cart.ts +"use server"; + +import { revalidateTag } from "next/cache"; +import { cookies } from "next/headers"; +import { redirect } from "next/navigation"; + +export async function addToCart(productId: string) { + const cookieStore = await cookies(); + const sessionId = cookieStore.get("session")?.value; + + if (!sessionId) { + redirect("/login"); + } + + try { + await db.cart.upsert({ + where: { sessionId_productId: { sessionId, productId } }, + update: { quantity: { increment: 1 } }, + create: { sessionId, productId, quantity: 1 }, + }); + + revalidateTag("cart"); + return { success: true }; + } catch (error) { + return { error: "Failed to add item to cart" }; + } +} + +export async function checkout(formData: FormData) { + const address = formData.get("address") as string; + const payment = formData.get("payment") as string; + + // Validate + if (!address || !payment) { + return { error: "Missing required fields" }; + } + + // Process order + const order = await processOrder({ address, payment }); + + // Redirect to confirmation + redirect(`/orders/${order.id}/confirmation`); +} +``` + +### Pattern 4: Parallel Routes + +```typescript +// app/dashboard/layout.tsx +export default function DashboardLayout({ + children, + analytics, + team, +}: { + children: React.ReactNode + analytics: React.ReactNode + team: React.ReactNode +}) { + return ( +
+
{children}
+ + +
+ ) +} + +// app/dashboard/@analytics/page.tsx +export default async function AnalyticsSlot() { + const stats = await getAnalytics() + return +} + +// app/dashboard/@analytics/loading.tsx +export default function AnalyticsLoading() { + return +} + +// app/dashboard/@team/page.tsx +export default async function TeamSlot() { + const members = await getTeamMembers() + return +} +``` + +### Pattern 5: Intercepting Routes (Modal Pattern) + +```typescript +// File structure for photo modal +// app/ +// ├── @modal/ +// │ ├── (.)photos/[id]/page.tsx # Intercept +// │ └── default.tsx +// ├── photos/ +// │ └── [id]/page.tsx # Full page +// └── layout.tsx + +// app/@modal/(.)photos/[id]/page.tsx +import { Modal } from '@/components/Modal' +import { PhotoDetail } from '@/components/PhotoDetail' + +export default async function PhotoModal({ + params, +}: { + params: Promise<{ id: string }> +}) { + const { id } = await params + const photo = await getPhoto(id) + + return ( + + + + ) +} + +// app/photos/[id]/page.tsx - Full page version +export default async function PhotoPage({ + params, +}: { + params: Promise<{ id: string }> +}) { + const { id } = await params + const photo = await getPhoto(id) + + return ( +
+ + +
+ ) +} + +// app/layout.tsx +export default function RootLayout({ + children, + modal, +}: { + children: React.ReactNode + modal: React.ReactNode +}) { + return ( + + + {children} + {modal} + + + ) +} +``` + +### Pattern 6: Streaming with Suspense + +```typescript +// app/product/[id]/page.tsx +import { Suspense } from 'react' + +export default async function ProductPage({ + params, +}: { + params: Promise<{ id: string }> +}) { + const { id } = await params + + // This data loads first (blocking) + const product = await getProduct(id) + + return ( +
+ {/* Immediate render */} + + + {/* Stream in reviews */} + }> + + + + {/* Stream in recommendations */} + }> + + +
+ ) +} + +// These components fetch their own data +async function Reviews({ productId }: { productId: string }) { + const reviews = await getReviews(productId) // Slow API + return +} + +async function Recommendations({ productId }: { productId: string }) { + const products = await getRecommendations(productId) // ML-based, slow + return +} +``` + +### Pattern 7: Route Handlers (API Routes) + +```typescript +// app/api/products/route.ts +import { NextRequest, NextResponse } from "next/server"; + +export async function GET(request: NextRequest) { + const searchParams = request.nextUrl.searchParams; + const category = searchParams.get("category"); + + const products = await db.product.findMany({ + where: category ? { category } : undefined, + take: 20, + }); + + return NextResponse.json(products); +} + +export async function POST(request: NextRequest) { + const body = await request.json(); + + const product = await db.product.create({ + data: body, + }); + + return NextResponse.json(product, { status: 201 }); +} + +// app/api/products/[id]/route.ts +export async function GET( + request: NextRequest, + { params }: { params: Promise<{ id: string }> }, +) { + const { id } = await params; + const product = await db.product.findUnique({ where: { id } }); + + if (!product) { + return NextResponse.json({ error: "Product not found" }, { status: 404 }); + } + + return NextResponse.json(product); +} +``` + +### Pattern 8: Metadata and SEO + +```typescript +// app/products/[slug]/page.tsx +import { Metadata } from 'next' +import { notFound } from 'next/navigation' + +type Props = { + params: Promise<{ slug: string }> +} + +export async function generateMetadata({ params }: Props): Promise { + const { slug } = await params + const product = await getProduct(slug) + + if (!product) return {} + + return { + title: product.name, + description: product.description, + openGraph: { + title: product.name, + description: product.description, + images: [{ url: product.image, width: 1200, height: 630 }], + }, + twitter: { + card: 'summary_large_image', + title: product.name, + description: product.description, + images: [product.image], + }, + } +} + +export async function generateStaticParams() { + const products = await db.product.findMany({ select: { slug: true } }) + return products.map((p) => ({ slug: p.slug })) +} + +export default async function ProductPage({ params }: Props) { + const { slug } = await params + const product = await getProduct(slug) + + if (!product) notFound() + + return +} +``` + +## Caching Strategies + +### Data Cache + +```typescript +// No cache (always fresh) +fetch(url, { cache: "no-store" }); + +// Cache forever (static) +fetch(url, { cache: "force-cache" }); + +// ISR - revalidate after 60 seconds +fetch(url, { next: { revalidate: 60 } }); + +// Tag-based invalidation +fetch(url, { next: { tags: ["products"] } }); + +// Invalidate via Server Action +("use server"); +import { revalidateTag, revalidatePath } from "next/cache"; + +export async function updateProduct(id: string, data: ProductData) { + await db.product.update({ where: { id }, data }); + revalidateTag("products"); + revalidatePath("/products"); +} +``` + +## Best Practices + +### Do's + +- **Start with Server Components** - Add 'use client' only when needed +- **Colocate data fetching** - Fetch data where it's used +- **Use Suspense boundaries** - Enable streaming for slow data +- **Leverage parallel routes** - Independent loading states +- **Use Server Actions** - For mutations with progressive enhancement + +### Don'ts + +- **Don't pass serializable data** - Server → Client boundary limitations +- **Don't use hooks in Server Components** - No useState, useEffect +- **Don't fetch in Client Components** - Use Server Components or React Query +- **Don't over-nest layouts** - Each layout adds to the component tree +- **Don't ignore loading states** - Always provide loading.tsx or Suspense + +## Resources + +- [Next.js App Router Documentation](https://nextjs.org/docs/app) +- [Server Components RFC](https://github.com/reactjs/rfcs/blob/main/text/0188-server-components.md) +- [Vercel Templates](https://vercel.com/templates/next.js) diff --git a/.agent/skills/vercel-react-best-practices/AGENTS.md b/.agent/skills/vercel-react-best-practices/AGENTS.md new file mode 100644 index 0000000..db951ab --- /dev/null +++ b/.agent/skills/vercel-react-best-practices/AGENTS.md @@ -0,0 +1,2934 @@ +# React Best Practices + +**Version 1.0.0** +Vercel Engineering +January 2026 + +> **Note:** +> This document is mainly for agents and LLMs to follow when maintaining, +> generating, or refactoring React and Next.js codebases. Humans +> may also find it useful, but guidance here is optimized for automation +> and consistency by AI-assisted workflows. + +--- + +## Abstract + +Comprehensive performance optimization guide for React and Next.js applications, designed for AI agents and LLMs. Contains 40+ rules across 8 categories, prioritized by impact from critical (eliminating waterfalls, reducing bundle size) to incremental (advanced patterns). Each rule includes detailed explanations, real-world examples comparing incorrect vs. correct implementations, and specific impact metrics to guide automated refactoring and code generation. + +--- + +## Table of Contents + +1. [Eliminating Waterfalls](#1-eliminating-waterfalls) — **CRITICAL** + - 1.1 [Defer Await Until Needed](#11-defer-await-until-needed) + - 1.2 [Dependency-Based Parallelization](#12-dependency-based-parallelization) + - 1.3 [Prevent Waterfall Chains in API Routes](#13-prevent-waterfall-chains-in-api-routes) + - 1.4 [Promise.all() for Independent Operations](#14-promiseall-for-independent-operations) + - 1.5 [Strategic Suspense Boundaries](#15-strategic-suspense-boundaries) +2. [Bundle Size Optimization](#2-bundle-size-optimization) — **CRITICAL** + - 2.1 [Avoid Barrel File Imports](#21-avoid-barrel-file-imports) + - 2.2 [Conditional Module Loading](#22-conditional-module-loading) + - 2.3 [Defer Non-Critical Third-Party Libraries](#23-defer-non-critical-third-party-libraries) + - 2.4 [Dynamic Imports for Heavy Components](#24-dynamic-imports-for-heavy-components) + - 2.5 [Preload Based on User Intent](#25-preload-based-on-user-intent) +3. [Server-Side Performance](#3-server-side-performance) — **HIGH** + - 3.1 [Authenticate Server Actions Like API Routes](#31-authenticate-server-actions-like-api-routes) + - 3.2 [Avoid Duplicate Serialization in RSC Props](#32-avoid-duplicate-serialization-in-rsc-props) + - 3.3 [Cross-Request LRU Caching](#33-cross-request-lru-caching) + - 3.4 [Minimize Serialization at RSC Boundaries](#34-minimize-serialization-at-rsc-boundaries) + - 3.5 [Parallel Data Fetching with Component Composition](#35-parallel-data-fetching-with-component-composition) + - 3.6 [Per-Request Deduplication with React.cache()](#36-per-request-deduplication-with-reactcache) + - 3.7 [Use after() for Non-Blocking Operations](#37-use-after-for-non-blocking-operations) +4. [Client-Side Data Fetching](#4-client-side-data-fetching) — **MEDIUM-HIGH** + - 4.1 [Deduplicate Global Event Listeners](#41-deduplicate-global-event-listeners) + - 4.2 [Use Passive Event Listeners for Scrolling Performance](#42-use-passive-event-listeners-for-scrolling-performance) + - 4.3 [Use SWR for Automatic Deduplication](#43-use-swr-for-automatic-deduplication) + - 4.4 [Version and Minimize localStorage Data](#44-version-and-minimize-localstorage-data) +5. [Re-render Optimization](#5-re-render-optimization) — **MEDIUM** + - 5.1 [Calculate Derived State During Rendering](#51-calculate-derived-state-during-rendering) + - 5.2 [Defer State Reads to Usage Point](#52-defer-state-reads-to-usage-point) + - 5.3 [Do not wrap a simple expression with a primitive result type in useMemo](#53-do-not-wrap-a-simple-expression-with-a-primitive-result-type-in-usememo) + - 5.4 [Extract Default Non-primitive Parameter Value from Memoized Component to Constant](#54-extract-default-non-primitive-parameter-value-from-memoized-component-to-constant) + - 5.5 [Extract to Memoized Components](#55-extract-to-memoized-components) + - 5.6 [Narrow Effect Dependencies](#56-narrow-effect-dependencies) + - 5.7 [Put Interaction Logic in Event Handlers](#57-put-interaction-logic-in-event-handlers) + - 5.8 [Subscribe to Derived State](#58-subscribe-to-derived-state) + - 5.9 [Use Functional setState Updates](#59-use-functional-setstate-updates) + - 5.10 [Use Lazy State Initialization](#510-use-lazy-state-initialization) + - 5.11 [Use Transitions for Non-Urgent Updates](#511-use-transitions-for-non-urgent-updates) + - 5.12 [Use useRef for Transient Values](#512-use-useref-for-transient-values) +6. [Rendering Performance](#6-rendering-performance) — **MEDIUM** + - 6.1 [Animate SVG Wrapper Instead of SVG Element](#61-animate-svg-wrapper-instead-of-svg-element) + - 6.2 [CSS content-visibility for Long Lists](#62-css-content-visibility-for-long-lists) + - 6.3 [Hoist Static JSX Elements](#63-hoist-static-jsx-elements) + - 6.4 [Optimize SVG Precision](#64-optimize-svg-precision) + - 6.5 [Prevent Hydration Mismatch Without Flickering](#65-prevent-hydration-mismatch-without-flickering) + - 6.6 [Suppress Expected Hydration Mismatches](#66-suppress-expected-hydration-mismatches) + - 6.7 [Use Activity Component for Show/Hide](#67-use-activity-component-for-showhide) + - 6.8 [Use Explicit Conditional Rendering](#68-use-explicit-conditional-rendering) + - 6.9 [Use useTransition Over Manual Loading States](#69-use-usetransition-over-manual-loading-states) +7. [JavaScript Performance](#7-javascript-performance) — **LOW-MEDIUM** + - 7.1 [Avoid Layout Thrashing](#71-avoid-layout-thrashing) + - 7.2 [Build Index Maps for Repeated Lookups](#72-build-index-maps-for-repeated-lookups) + - 7.3 [Cache Property Access in Loops](#73-cache-property-access-in-loops) + - 7.4 [Cache Repeated Function Calls](#74-cache-repeated-function-calls) + - 7.5 [Cache Storage API Calls](#75-cache-storage-api-calls) + - 7.6 [Combine Multiple Array Iterations](#76-combine-multiple-array-iterations) + - 7.7 [Early Length Check for Array Comparisons](#77-early-length-check-for-array-comparisons) + - 7.8 [Early Return from Functions](#78-early-return-from-functions) + - 7.9 [Hoist RegExp Creation](#79-hoist-regexp-creation) + - 7.10 [Use Loop for Min/Max Instead of Sort](#710-use-loop-for-minmax-instead-of-sort) + - 7.11 [Use Set/Map for O(1) Lookups](#711-use-setmap-for-o1-lookups) + - 7.12 [Use toSorted() Instead of sort() for Immutability](#712-use-tosorted-instead-of-sort-for-immutability) +8. [Advanced Patterns](#8-advanced-patterns) — **LOW** + - 8.1 [Initialize App Once, Not Per Mount](#81-initialize-app-once-not-per-mount) + - 8.2 [Store Event Handlers in Refs](#82-store-event-handlers-in-refs) + - 8.3 [useEffectEvent for Stable Callback Refs](#83-useeffectevent-for-stable-callback-refs) + +--- + +## 1. Eliminating Waterfalls + +**Impact: CRITICAL** + +Waterfalls are the #1 performance killer. Each sequential await adds full network latency. Eliminating them yields the largest gains. + +### 1.1 Defer Await Until Needed + +**Impact: HIGH (avoids blocking unused code paths)** + +Move `await` operations into the branches where they're actually used to avoid blocking code paths that don't need them. + +**Incorrect: blocks both branches** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + const userData = await fetchUserData(userId) + + if (skipProcessing) { + // Returns immediately but still waited for userData + return { skipped: true } + } + + // Only this branch uses userData + return processUserData(userData) +} +``` + +**Correct: only blocks when needed** + +```typescript +async function handleRequest(userId: string, skipProcessing: boolean) { + if (skipProcessing) { + // Returns immediately without waiting + return { skipped: true } + } + + // Fetch only when needed + const userData = await fetchUserData(userId) + return processUserData(userData) +} +``` + +**Another example: early return optimization** + +```typescript +// Incorrect: always fetches permissions +async function updateResource(resourceId: string, userId: string) { + const permissions = await fetchPermissions(userId) + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} + +// Correct: fetches only when needed +async function updateResource(resourceId: string, userId: string) { + const resource = await getResource(resourceId) + + if (!resource) { + return { error: 'Not found' } + } + + const permissions = await fetchPermissions(userId) + + if (!permissions.canEdit) { + return { error: 'Forbidden' } + } + + return await updateResourceData(resource, permissions) +} +``` + +This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive. + +### 1.2 Dependency-Based Parallelization + +**Impact: CRITICAL (2-10× improvement)** + +For operations with partial dependencies, use `better-all` to maximize parallelism. It automatically starts each task at the earliest possible moment. + +**Incorrect: profile waits for config unnecessarily** + +```typescript +const [user, config] = await Promise.all([ + fetchUser(), + fetchConfig() +]) +const profile = await fetchProfile(user.id) +``` + +**Correct: config and profile run in parallel** + +```typescript +import { all } from 'better-all' + +const { user, config, profile } = await all({ + async user() { return fetchUser() }, + async config() { return fetchConfig() }, + async profile() { + return fetchProfile((await this.$.user).id) + } +}) +``` + +**Alternative without extra dependencies:** + +```typescript +const userPromise = fetchUser() +const profilePromise = userPromise.then(user => fetchProfile(user.id)) + +const [user, config, profile] = await Promise.all([ + userPromise, + fetchConfig(), + profilePromise +]) +``` + +We can also create all the promises first, and do `Promise.all()` at the end. + +Reference: [https://github.com/shuding/better-all](https://github.com/shuding/better-all) + +### 1.3 Prevent Waterfall Chains in API Routes + +**Impact: CRITICAL (2-10× improvement)** + +In API routes and Server Actions, start independent operations immediately, even if you don't await them yet. + +**Incorrect: config waits for auth, data waits for both** + +```typescript +export async function GET(request: Request) { + const session = await auth() + const config = await fetchConfig() + const data = await fetchData(session.user.id) + return Response.json({ data, config }) +} +``` + +**Correct: auth and config start immediately** + +```typescript +export async function GET(request: Request) { + const sessionPromise = auth() + const configPromise = fetchConfig() + const session = await sessionPromise + const [config, data] = await Promise.all([ + configPromise, + fetchData(session.user.id) + ]) + return Response.json({ data, config }) +} +``` + +For operations with more complex dependency chains, use `better-all` to automatically maximize parallelism (see Dependency-Based Parallelization). + +### 1.4 Promise.all() for Independent Operations + +**Impact: CRITICAL (2-10× improvement)** + +When async operations have no interdependencies, execute them concurrently using `Promise.all()`. + +**Incorrect: sequential execution, 3 round trips** + +```typescript +const user = await fetchUser() +const posts = await fetchPosts() +const comments = await fetchComments() +``` + +**Correct: parallel execution, 1 round trip** + +```typescript +const [user, posts, comments] = await Promise.all([ + fetchUser(), + fetchPosts(), + fetchComments() +]) +``` + +### 1.5 Strategic Suspense Boundaries + +**Impact: HIGH (faster initial paint)** + +Instead of awaiting data in async components before returning JSX, use Suspense boundaries to show the wrapper UI faster while data loads. + +**Incorrect: wrapper blocked by data fetching** + +```tsx +async function Page() { + const data = await fetchData() // Blocks entire page + + return ( +
+
Sidebar
+
Header
+
+ +
+
Footer
+
+ ) +} +``` + +The entire layout waits for data even though only the middle section needs it. + +**Correct: wrapper shows immediately, data streams in** + +```tsx +function Page() { + return ( +
+
Sidebar
+
Header
+
+ }> + + +
+
Footer
+
+ ) +} + +async function DataDisplay() { + const data = await fetchData() // Only blocks this component + return
{data.content}
+} +``` + +Sidebar, Header, and Footer render immediately. Only DataDisplay waits for data. + +**Alternative: share promise across components** + +```tsx +function Page() { + // Start fetch immediately, but don't await + const dataPromise = fetchData() + + return ( +
+
Sidebar
+
Header
+ }> + + + +
Footer
+
+ ) +} + +function DataDisplay({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Unwraps the promise + return
{data.content}
+} + +function DataSummary({ dataPromise }: { dataPromise: Promise }) { + const data = use(dataPromise) // Reuses the same promise + return
{data.summary}
+} +``` + +Both components share the same promise, so only one fetch occurs. Layout renders immediately while both components wait together. + +**When NOT to use this pattern:** + +- Critical data needed for layout decisions (affects positioning) + +- SEO-critical content above the fold + +- Small, fast queries where suspense overhead isn't worth it + +- When you want to avoid layout shift (loading → content jump) + +**Trade-off:** Faster initial paint vs potential layout shift. Choose based on your UX priorities. + +--- + +## 2. Bundle Size Optimization + +**Impact: CRITICAL** + +Reducing initial bundle size improves Time to Interactive and Largest Contentful Paint. + +### 2.1 Avoid Barrel File Imports + +**Impact: CRITICAL (200-800ms import cost, slow builds)** + +Import directly from source files instead of barrel files to avoid loading thousands of unused modules. **Barrel files** are entry points that re-export multiple modules (e.g., `index.js` that does `export * from './module'`). + +Popular icon and component libraries can have **up to 10,000 re-exports** in their entry file. For many React packages, **it takes 200-800ms just to import them**, affecting both development speed and production cold starts. + +**Why tree-shaking doesn't help:** When a library is marked as external (not bundled), the bundler can't optimize it. If you bundle it to enable tree-shaking, builds become substantially slower analyzing the entire module graph. + +**Incorrect: imports entire library** + +```tsx +import { Check, X, Menu } from 'lucide-react' +// Loads 1,583 modules, takes ~2.8s extra in dev +// Runtime cost: 200-800ms on every cold start + +import { Button, TextField } from '@mui/material' +// Loads 2,225 modules, takes ~4.2s extra in dev +``` + +**Correct: imports only what you need** + +```tsx +import Check from 'lucide-react/dist/esm/icons/check' +import X from 'lucide-react/dist/esm/icons/x' +import Menu from 'lucide-react/dist/esm/icons/menu' +// Loads only 3 modules (~2KB vs ~1MB) + +import Button from '@mui/material/Button' +import TextField from '@mui/material/TextField' +// Loads only what you use +``` + +**Alternative: Next.js 13.5+** + +```js +// next.config.js - use optimizePackageImports +module.exports = { + experimental: { + optimizePackageImports: ['lucide-react', '@mui/material'] + } +} + +// Then you can keep the ergonomic barrel imports: +import { Check, X, Menu } from 'lucide-react' +// Automatically transformed to direct imports at build time +``` + +Direct imports provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR. + +Libraries commonly affected: `lucide-react`, `@mui/material`, `@mui/icons-material`, `@tabler/icons-react`, `react-icons`, `@headlessui/react`, `@radix-ui/react-*`, `lodash`, `ramda`, `date-fns`, `rxjs`, `react-use`. + +Reference: [https://vercel.com/blog/how-we-optimized-package-imports-in-next-js](https://vercel.com/blog/how-we-optimized-package-imports-in-next-js) + +### 2.2 Conditional Module Loading + +**Impact: HIGH (loads large data only when needed)** + +Load large data or modules only when a feature is activated. + +**Example: lazy-load animation frames** + +```tsx +function AnimationPlayer({ enabled, setEnabled }: { enabled: boolean; setEnabled: React.Dispatch> }) { + const [frames, setFrames] = useState(null) + + useEffect(() => { + if (enabled && !frames && typeof window !== 'undefined') { + import('./animation-frames.js') + .then(mod => setFrames(mod.frames)) + .catch(() => setEnabled(false)) + } + }, [enabled, frames, setEnabled]) + + if (!frames) return + return +} +``` + +The `typeof window !== 'undefined'` check prevents bundling this module for SSR, optimizing server bundle size and build speed. + +### 2.3 Defer Non-Critical Third-Party Libraries + +**Impact: MEDIUM (loads after hydration)** + +Analytics, logging, and error tracking don't block user interaction. Load them after hydration. + +**Incorrect: blocks initial bundle** + +```tsx +import { Analytics } from '@vercel/analytics/react' + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +**Correct: loads after hydration** + +```tsx +import dynamic from 'next/dynamic' + +const Analytics = dynamic( + () => import('@vercel/analytics/react').then(m => m.Analytics), + { ssr: false } +) + +export default function RootLayout({ children }) { + return ( + + + {children} + + + + ) +} +``` + +### 2.4 Dynamic Imports for Heavy Components + +**Impact: CRITICAL (directly affects TTI and LCP)** + +Use `next/dynamic` to lazy-load large components not needed on initial render. + +**Incorrect: Monaco bundles with main chunk ~300KB** + +```tsx +import { MonacoEditor } from './monaco-editor' + +function CodePanel({ code }: { code: string }) { + return +} +``` + +**Correct: Monaco loads on demand** + +```tsx +import dynamic from 'next/dynamic' + +const MonacoEditor = dynamic( + () => import('./monaco-editor').then(m => m.MonacoEditor), + { ssr: false } +) + +function CodePanel({ code }: { code: string }) { + return +} +``` + +### 2.5 Preload Based on User Intent + +**Impact: MEDIUM (reduces perceived latency)** + +Preload heavy bundles before they're needed to reduce perceived latency. + +**Example: preload on hover/focus** + +```tsx +function EditorButton({ onClick }: { onClick: () => void }) { + const preload = () => { + if (typeof window !== 'undefined') { + void import('./monaco-editor') + } + } + + return ( + + ) +} +``` + +**Example: preload when feature flag is enabled** + +```tsx +function FlagsProvider({ children, flags }: Props) { + useEffect(() => { + if (flags.editorEnabled && typeof window !== 'undefined') { + void import('./monaco-editor').then(mod => mod.init()) + } + }, [flags.editorEnabled]) + + return + {children} + +} +``` + +The `typeof window !== 'undefined'` check prevents bundling preloaded modules for SSR, optimizing server bundle size and build speed. + +--- + +## 3. Server-Side Performance + +**Impact: HIGH** + +Optimizing server-side rendering and data fetching eliminates server-side waterfalls and reduces response times. + +### 3.1 Authenticate Server Actions Like API Routes + +**Impact: CRITICAL (prevents unauthorized access to server mutations)** + +Server Actions (functions with `"use server"`) are exposed as public endpoints, just like API routes. Always verify authentication and authorization **inside** each Server Action—do not rely solely on middleware, layout guards, or page-level checks, as Server Actions can be invoked directly. + +Next.js documentation explicitly states: "Treat Server Actions with the same security considerations as public-facing API endpoints, and verify if the user is allowed to perform a mutation." + +**Incorrect: no authentication check** + +```typescript +'use server' + +export async function deleteUser(userId: string) { + // Anyone can call this! No auth check + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**Correct: authentication inside the action** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { unauthorized } from '@/lib/errors' + +export async function deleteUser(userId: string) { + // Always check auth inside the action + const session = await verifySession() + + if (!session) { + throw unauthorized('Must be logged in') + } + + // Check authorization too + if (session.user.role !== 'admin' && session.user.id !== userId) { + throw unauthorized('Cannot delete other users') + } + + await db.user.delete({ where: { id: userId } }) + return { success: true } +} +``` + +**With input validation:** + +```typescript +'use server' + +import { verifySession } from '@/lib/auth' +import { z } from 'zod' + +const updateProfileSchema = z.object({ + userId: z.string().uuid(), + name: z.string().min(1).max(100), + email: z.string().email() +}) + +export async function updateProfile(data: unknown) { + // Validate input first + const validated = updateProfileSchema.parse(data) + + // Then authenticate + const session = await verifySession() + if (!session) { + throw new Error('Unauthorized') + } + + // Then authorize + if (session.user.id !== validated.userId) { + throw new Error('Can only update own profile') + } + + // Finally perform the mutation + await db.user.update({ + where: { id: validated.userId }, + data: { + name: validated.name, + email: validated.email + } + }) + + return { success: true } +} +``` + +Reference: [https://nextjs.org/docs/app/guides/authentication](https://nextjs.org/docs/app/guides/authentication) + +### 3.2 Avoid Duplicate Serialization in RSC Props + +**Impact: LOW (reduces network payload by avoiding duplicate serialization)** + +RSC→client serialization deduplicates by object reference, not value. Same reference = serialized once; new reference = serialized again. Do transformations (`.toSorted()`, `.filter()`, `.map()`) in client, not server. + +**Incorrect: duplicates array** + +```tsx +// RSC: sends 6 strings (2 arrays × 3 items) + +``` + +**Correct: sends 3 strings** + +```tsx +// RSC: send once + + +// Client: transform there +'use client' +const sorted = useMemo(() => [...usernames].sort(), [usernames]) +``` + +**Nested deduplication behavior:** + +```tsx +// string[] - duplicates everything +usernames={['a','b']} sorted={usernames.toSorted()} // sends 4 strings + +// object[] - duplicates array structure only +users={[{id:1},{id:2}]} sorted={users.toSorted()} // sends 2 arrays + 2 unique objects (not 4) +``` + +Deduplication works recursively. Impact varies by data type: + +- `string[]`, `number[]`, `boolean[]`: **HIGH impact** - array + all primitives fully duplicated + +- `object[]`: **LOW impact** - array duplicated, but nested objects deduplicated by reference + +**Operations breaking deduplication: create new references** + +- Arrays: `.toSorted()`, `.filter()`, `.map()`, `.slice()`, `[...arr]` + +- Objects: `{...obj}`, `Object.assign()`, `structuredClone()`, `JSON.parse(JSON.stringify())` + +**More examples:** + +```tsx +// ❌ Bad + u.active)} /> + + +// ✅ Good + + +// Do filtering/destructuring in client +``` + +**Exception:** Pass derived data when transformation is expensive or client doesn't need original. + +### 3.3 Cross-Request LRU Caching + +**Impact: HIGH (caches across requests)** + +`React.cache()` only works within one request. For data shared across sequential requests (user clicks button A then button B), use an LRU cache. + +**Implementation:** + +```typescript +import { LRUCache } from 'lru-cache' + +const cache = new LRUCache({ + max: 1000, + ttl: 5 * 60 * 1000 // 5 minutes +}) + +export async function getUser(id: string) { + const cached = cache.get(id) + if (cached) return cached + + const user = await db.user.findUnique({ where: { id } }) + cache.set(id, user) + return user +} + +// Request 1: DB query, result cached +// Request 2: cache hit, no DB query +``` + +Use when sequential user actions hit multiple endpoints needing the same data within seconds. + +**With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute):** LRU caching is especially effective because multiple concurrent requests can share the same function instance and cache. This means the cache persists across requests without needing external storage like Redis. + +**In traditional serverless:** Each invocation runs in isolation, so consider Redis for cross-process caching. + +Reference: [https://github.com/isaacs/node-lru-cache](https://github.com/isaacs/node-lru-cache) + +### 3.4 Minimize Serialization at RSC Boundaries + +**Impact: HIGH (reduces data transfer size)** + +The React Server/Client boundary serializes all object properties into strings and embeds them in the HTML response and subsequent RSC requests. This serialized data directly impacts page weight and load time, so **size matters a lot**. Only pass fields that the client actually uses. + +**Incorrect: serializes all 50 fields** + +```tsx +async function Page() { + const user = await fetchUser() // 50 fields + return +} + +'use client' +function Profile({ user }: { user: User }) { + return
{user.name}
// uses 1 field +} +``` + +**Correct: serializes only 1 field** + +```tsx +async function Page() { + const user = await fetchUser() + return +} + +'use client' +function Profile({ name }: { name: string }) { + return
{name}
+} +``` + +### 3.5 Parallel Data Fetching with Component Composition + +**Impact: CRITICAL (eliminates server-side waterfalls)** + +React Server Components execute sequentially within a tree. Restructure with composition to parallelize data fetching. + +**Incorrect: Sidebar waits for Page's fetch to complete** + +```tsx +export default async function Page() { + const header = await fetchHeader() + return ( +
+
{header}
+ +
+ ) +} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} +``` + +**Correct: both fetch simultaneously** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +export default function Page() { + return ( +
+
+ +
+ ) +} +``` + +**Alternative with children prop:** + +```tsx +async function Header() { + const data = await fetchHeader() + return
{data}
+} + +async function Sidebar() { + const items = await fetchSidebarItems() + return +} + +function Layout({ children }: { children: ReactNode }) { + return ( +
+
+ {children} +
+ ) +} + +export default function Page() { + return ( + + + + ) +} +``` + +### 3.6 Per-Request Deduplication with React.cache() + +**Impact: MEDIUM (deduplicates within request)** + +Use `React.cache()` for server-side request deduplication. Authentication and database queries benefit most. + +**Usage:** + +```typescript +import { cache } from 'react' + +export const getCurrentUser = cache(async () => { + const session = await auth() + if (!session?.user?.id) return null + return await db.user.findUnique({ + where: { id: session.user.id } + }) +}) +``` + +Within a single request, multiple calls to `getCurrentUser()` execute the query only once. + +**Avoid inline objects as arguments:** + +`React.cache()` uses shallow equality (`Object.is`) to determine cache hits. Inline objects create new references each call, preventing cache hits. + +**Incorrect: always cache miss** + +```typescript +const getUser = cache(async (params: { uid: number }) => { + return await db.user.findUnique({ where: { id: params.uid } }) +}) + +// Each call creates new object, never hits cache +getUser({ uid: 1 }) +getUser({ uid: 1 }) // Cache miss, runs query again +``` + +**Correct: cache hit** + +```typescript +const params = { uid: 1 } +getUser(params) // Query runs +getUser(params) // Cache hit (same reference) +``` + +If you must pass objects, pass the same reference: + +**Next.js-Specific Note:** + +In Next.js, the `fetch` API is automatically extended with request memoization. Requests with the same URL and options are automatically deduplicated within a single request, so you don't need `React.cache()` for `fetch` calls. However, `React.cache()` is still essential for other async tasks: + +- Database queries (Prisma, Drizzle, etc.) + +- Heavy computations + +- Authentication checks + +- File system operations + +- Any non-fetch async work + +Use `React.cache()` to deduplicate these operations across your component tree. + +Reference: [https://react.dev/reference/react/cache](https://react.dev/reference/react/cache) + +### 3.7 Use after() for Non-Blocking Operations + +**Impact: MEDIUM (faster response times)** + +Use Next.js's `after()` to schedule work that should execute after a response is sent. This prevents logging, analytics, and other side effects from blocking the response. + +**Incorrect: blocks response** + +```tsx +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Logging blocks the response + const userAgent = request.headers.get('user-agent') || 'unknown' + await logUserAction({ userAgent }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +**Correct: non-blocking** + +```tsx +import { after } from 'next/server' +import { headers, cookies } from 'next/headers' +import { logUserAction } from '@/app/utils' + +export async function POST(request: Request) { + // Perform mutation + await updateDatabase(request) + + // Log after response is sent + after(async () => { + const userAgent = (await headers()).get('user-agent') || 'unknown' + const sessionCookie = (await cookies()).get('session-id')?.value || 'anonymous' + + logUserAction({ sessionCookie, userAgent }) + }) + + return new Response(JSON.stringify({ status: 'success' }), { + status: 200, + headers: { 'Content-Type': 'application/json' } + }) +} +``` + +The response is sent immediately while logging happens in the background. + +**Common use cases:** + +- Analytics tracking + +- Audit logging + +- Sending notifications + +- Cache invalidation + +- Cleanup tasks + +**Important notes:** + +- `after()` runs even if the response fails or redirects + +- Works in Server Actions, Route Handlers, and Server Components + +Reference: [https://nextjs.org/docs/app/api-reference/functions/after](https://nextjs.org/docs/app/api-reference/functions/after) + +--- + +## 4. Client-Side Data Fetching + +**Impact: MEDIUM-HIGH** + +Automatic deduplication and efficient data fetching patterns reduce redundant network requests. + +### 4.1 Deduplicate Global Event Listeners + +**Impact: LOW (single listener for N components)** + +Use `useSWRSubscription()` to share global event listeners across component instances. + +**Incorrect: N instances = N listeners** + +```tsx +function useKeyboardShortcut(key: string, callback: () => void) { + useEffect(() => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && e.key === key) { + callback() + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }, [key, callback]) +} +``` + +When using the `useKeyboardShortcut` hook multiple times, each instance will register a new listener. + +**Correct: N instances = 1 listener** + +```tsx +import useSWRSubscription from 'swr/subscription' + +// Module-level Map to track callbacks per key +const keyCallbacks = new Map void>>() + +function useKeyboardShortcut(key: string, callback: () => void) { + // Register this callback in the Map + useEffect(() => { + if (!keyCallbacks.has(key)) { + keyCallbacks.set(key, new Set()) + } + keyCallbacks.get(key)!.add(callback) + + return () => { + const set = keyCallbacks.get(key) + if (set) { + set.delete(callback) + if (set.size === 0) { + keyCallbacks.delete(key) + } + } + } + }, [key, callback]) + + useSWRSubscription('global-keydown', () => { + const handler = (e: KeyboardEvent) => { + if (e.metaKey && keyCallbacks.has(e.key)) { + keyCallbacks.get(e.key)!.forEach(cb => cb()) + } + } + window.addEventListener('keydown', handler) + return () => window.removeEventListener('keydown', handler) + }) +} + +function Profile() { + // Multiple shortcuts will share the same listener + useKeyboardShortcut('p', () => { /* ... */ }) + useKeyboardShortcut('k', () => { /* ... */ }) + // ... +} +``` + +### 4.2 Use Passive Event Listeners for Scrolling Performance + +**Impact: MEDIUM (eliminates scroll delay caused by event listeners)** + +Add `{ passive: true }` to touch and wheel event listeners to enable immediate scrolling. Browsers normally wait for listeners to finish to check if `preventDefault()` is called, causing scroll delay. + +**Incorrect:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch) + document.addEventListener('wheel', handleWheel) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Correct:** + +```typescript +useEffect(() => { + const handleTouch = (e: TouchEvent) => console.log(e.touches[0].clientX) + const handleWheel = (e: WheelEvent) => console.log(e.deltaY) + + document.addEventListener('touchstart', handleTouch, { passive: true }) + document.addEventListener('wheel', handleWheel, { passive: true }) + + return () => { + document.removeEventListener('touchstart', handleTouch) + document.removeEventListener('wheel', handleWheel) + } +}, []) +``` + +**Use passive when:** tracking/analytics, logging, any listener that doesn't call `preventDefault()`. + +**Don't use passive when:** implementing custom swipe gestures, custom zoom controls, or any listener that needs `preventDefault()`. + +### 4.3 Use SWR for Automatic Deduplication + +**Impact: MEDIUM-HIGH (automatic deduplication)** + +SWR enables request deduplication, caching, and revalidation across component instances. + +**Incorrect: no deduplication, each instance fetches** + +```tsx +function UserList() { + const [users, setUsers] = useState([]) + useEffect(() => { + fetch('/api/users') + .then(r => r.json()) + .then(setUsers) + }, []) +} +``` + +**Correct: multiple instances share one request** + +```tsx +import useSWR from 'swr' + +function UserList() { + const { data: users } = useSWR('/api/users', fetcher) +} +``` + +**For immutable data:** + +```tsx +import { useImmutableSWR } from '@/lib/swr' + +function StaticContent() { + const { data } = useImmutableSWR('/api/config', fetcher) +} +``` + +**For mutations:** + +```tsx +import { useSWRMutation } from 'swr/mutation' + +function UpdateButton() { + const { trigger } = useSWRMutation('/api/user', updateUser) + return +} +``` + +Reference: [https://swr.vercel.app](https://swr.vercel.app) + +### 4.4 Version and Minimize localStorage Data + +**Impact: MEDIUM (prevents schema conflicts, reduces storage size)** + +Add version prefix to keys and store only needed fields. Prevents schema conflicts and accidental storage of sensitive data. + +**Incorrect:** + +```typescript +// No version, stores everything, no error handling +localStorage.setItem('userConfig', JSON.stringify(fullUserObject)) +const data = localStorage.getItem('userConfig') +``` + +**Correct:** + +```typescript +const VERSION = 'v2' + +function saveConfig(config: { theme: string; language: string }) { + try { + localStorage.setItem(`userConfig:${VERSION}`, JSON.stringify(config)) + } catch { + // Throws in incognito/private browsing, quota exceeded, or disabled + } +} + +function loadConfig() { + try { + const data = localStorage.getItem(`userConfig:${VERSION}`) + return data ? JSON.parse(data) : null + } catch { + return null + } +} + +// Migration from v1 to v2 +function migrate() { + try { + const v1 = localStorage.getItem('userConfig:v1') + if (v1) { + const old = JSON.parse(v1) + saveConfig({ theme: old.darkMode ? 'dark' : 'light', language: old.lang }) + localStorage.removeItem('userConfig:v1') + } + } catch {} +} +``` + +**Store minimal fields from server responses:** + +```typescript +// User object has 20+ fields, only store what UI needs +function cachePrefs(user: FullUser) { + try { + localStorage.setItem('prefs:v1', JSON.stringify({ + theme: user.preferences.theme, + notifications: user.preferences.notifications + })) + } catch {} +} +``` + +**Always wrap in try-catch:** `getItem()` and `setItem()` throw in incognito/private browsing (Safari, Firefox), when quota exceeded, or when disabled. + +**Benefits:** Schema evolution via versioning, reduced storage size, prevents storing tokens/PII/internal flags. + +--- + +## 5. Re-render Optimization + +**Impact: MEDIUM** + +Reducing unnecessary re-renders minimizes wasted computation and improves UI responsiveness. + +### 5.1 Calculate Derived State During Rendering + +**Impact: MEDIUM (avoids redundant renders and state drift)** + +If a value can be computed from current props/state, do not store it in state or update it in an effect. Derive it during render to avoid extra renders and state drift. Do not set state in effects solely in response to prop changes; prefer derived values or keyed resets instead. + +**Incorrect: redundant state and effect** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const [fullName, setFullName] = useState('') + + useEffect(() => { + setFullName(firstName + ' ' + lastName) + }, [firstName, lastName]) + + return

{fullName}

+} +``` + +**Correct: derive during render** + +```tsx +function Form() { + const [firstName, setFirstName] = useState('First') + const [lastName, setLastName] = useState('Last') + const fullName = firstName + ' ' + lastName + + return

{fullName}

+} +``` + +Reference: [https://react.dev/learn/you-might-not-need-an-effect](https://react.dev/learn/you-might-not-need-an-effect) + +### 5.2 Defer State Reads to Usage Point + +**Impact: MEDIUM (avoids unnecessary subscriptions)** + +Don't subscribe to dynamic state (searchParams, localStorage) if you only read it inside callbacks. + +**Incorrect: subscribes to all searchParams changes** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const searchParams = useSearchParams() + + const handleShare = () => { + const ref = searchParams.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +**Correct: reads on demand, no subscription** + +```tsx +function ShareButton({ chatId }: { chatId: string }) { + const handleShare = () => { + const params = new URLSearchParams(window.location.search) + const ref = params.get('ref') + shareChat(chatId, { ref }) + } + + return +} +``` + +### 5.3 Do not wrap a simple expression with a primitive result type in useMemo + +**Impact: LOW-MEDIUM (wasted computation on every render)** + +When an expression is simple (few logical or arithmetical operators) and has a primitive result type (boolean, number, string), do not wrap it in `useMemo`. + +Calling `useMemo` and comparing hook dependencies may consume more resources than the expression itself. + +**Incorrect:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = useMemo(() => { + return user.isLoading || notifications.isLoading + }, [user.isLoading, notifications.isLoading]) + + if (isLoading) return + // return some markup +} +``` + +**Correct:** + +```tsx +function Header({ user, notifications }: Props) { + const isLoading = user.isLoading || notifications.isLoading + + if (isLoading) return + // return some markup +} +``` + +### 5.4 Extract Default Non-primitive Parameter Value from Memoized Component to Constant + +**Impact: MEDIUM (restores memoization by using a constant for default value)** + +When memoized component has a default value for some non-primitive optional parameter, such as an array, function, or object, calling the component without that parameter results in broken memoization. This is because new value instances are created on every rerender, and they do not pass strict equality comparison in `memo()`. + +To address this issue, extract the default value into a constant. + +**Incorrect: `onClick` has different values on every rerender** + +```tsx +const UserAvatar = memo(function UserAvatar({ onClick = () => {} }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +**Correct: stable default value** + +```tsx +const NOOP = () => {}; + +const UserAvatar = memo(function UserAvatar({ onClick = NOOP }: { onClick?: () => void }) { + // ... +}) + +// Used without optional onClick + +``` + +### 5.5 Extract to Memoized Components + +**Impact: MEDIUM (enables early returns)** + +Extract expensive work into memoized components to enable early returns before computation. + +**Incorrect: computes avatar even when loading** + +```tsx +function Profile({ user, loading }: Props) { + const avatar = useMemo(() => { + const id = computeAvatarId(user) + return + }, [user]) + + if (loading) return + return
{avatar}
+} +``` + +**Correct: skips computation when loading** + +```tsx +const UserAvatar = memo(function UserAvatar({ user }: { user: User }) { + const id = useMemo(() => computeAvatarId(user), [user]) + return +}) + +function Profile({ user, loading }: Props) { + if (loading) return + return ( +
+ +
+ ) +} +``` + +**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, manual memoization with `memo()` and `useMemo()` is not necessary. The compiler automatically optimizes re-renders. + +### 5.6 Narrow Effect Dependencies + +**Impact: LOW (minimizes effect re-runs)** + +Specify primitive dependencies instead of objects to minimize effect re-runs. + +**Incorrect: re-runs on any user field change** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user]) +``` + +**Correct: re-runs only when id changes** + +```tsx +useEffect(() => { + console.log(user.id) +}, [user.id]) +``` + +**For derived state, compute outside effect:** + +```tsx +// Incorrect: runs on width=767, 766, 765... +useEffect(() => { + if (width < 768) { + enableMobileMode() + } +}, [width]) + +// Correct: runs only on boolean transition +const isMobile = width < 768 +useEffect(() => { + if (isMobile) { + enableMobileMode() + } +}, [isMobile]) +``` + +### 5.7 Put Interaction Logic in Event Handlers + +**Impact: MEDIUM (avoids effect re-runs and duplicate side effects)** + +If a side effect is triggered by a specific user action (submit, click, drag), run it in that event handler. Do not model the action as state + effect; it makes effects re-run on unrelated changes and can duplicate the action. + +**Incorrect: event modeled as state + effect** + +```tsx +function Form() { + const [submitted, setSubmitted] = useState(false) + const theme = useContext(ThemeContext) + + useEffect(() => { + if (submitted) { + post('/api/register') + showToast('Registered', theme) + } + }, [submitted, theme]) + + return +} +``` + +**Correct: do it in the handler** + +```tsx +function Form() { + const theme = useContext(ThemeContext) + + function handleSubmit() { + post('/api/register') + showToast('Registered', theme) + } + + return +} +``` + +Reference: [https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler) + +### 5.8 Subscribe to Derived State + +**Impact: MEDIUM (reduces re-render frequency)** + +Subscribe to derived boolean state instead of continuous values to reduce re-render frequency. + +**Incorrect: re-renders on every pixel change** + +```tsx +function Sidebar() { + const width = useWindowWidth() // updates continuously + const isMobile = width < 768 + return