매칭되면 버튼 선택(setShapeNum) 후, shapeNum 이 matched 로 커밋된 뒤
[shapeNum] effect 에서 handleSave(설정완료)를 자동 호출해 지붕형상까지 적용한다.
마운트 effect 에서 즉시 호출하면 stale shapeNum(기본값 1)으로 잘못된 패턴이
적용되므로 autoSaveShapeNumRef 가드 + 별도 effect 경유로 처리.
매칭 결과는 콘솔에 '✅ N번 버튼 매칭 → 자동 선택 + 설정완료' / '❌ 매칭 없음'
한 줄로 명시. CLAUDE.md PDF-import 절을 'pre-select만 → 설정완료 자동 적용'으로 갱신.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
[작업내용] :
- 마운트 시 pdfRoofShapeDescriptorState → matchRoofShapePattern → setShapeNum(매칭 버튼 pre-select)
- pre-select only: handleSave 비자동(사용자 [적용])
- consume-once: 매칭 시도 후 atom 리셋(비-PDF 재진입 stale 방지)
- 매처 null(복합형) 시 강제 선택 없이 기본값 유지
- 런타임(실제 분기별 pre-select) 수동 검증 잔여
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- pdfRoofShapeDescriptorState atom 추가(outerLineAtom)
- analyzePdfAndApply: 분석 시작 시 리셋 + payload.roofShape 저장
- 소비(매칭·pre-select)는 다음 task
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- raw 지붕형상 출력 → RoofShapeDescriptor(type/ridge/flows/confidence?) 정규화
- 어휘 밖 type/ridge 는 ''(매처 결측 관대), flows 는 어휘만 소문자화·중복제거
- 모두 비면 null, direction 비산출(매처 미사용)
- route.js 배선은 다음 task
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- descriptor(type/ridge/flows)→shapeNum|null 순수 매칭 함수
- flows 집합 1차 키 + type/ridge guard(모순 거부, 결측 관대)
- 폴백 null(autoMatchable=false인 4 비반환), confidence 무시
- Gemini 분석 확장(B)·자동 클릭 배선(C)은 다음 작업으로 분리
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- matchRoofShapePattern 단일 Task TDD 플랜(하니스 8불변식)
- flows 집합 키 + type/ridge guard, 폴백 null
- Gemini 분석 확장·자동 클릭은 후속 작업으로 명시
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- matchRoofShapePattern(descriptor)→shapeNum|null 순수 함수 설계
- 매칭 키 flows 집합(1차) + type/ridge guard(모순 거부)
- 폴백 null(4 비반환), confidence 무시 — UX 정책은 C 단계 위임
- 검증: scratchpad .mjs 불변식 하니스 8종
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- PDF 분석→지붕형상 자동 매칭의 선행 단계로 8패턴 카탈로그 설계 정의
- 매칭 키: type+ridge+flows(화면축) 시그니처, flows 집합만으로 8패턴 유일 식별
- 5~8 화면축↔버튼 매핑을 useRoofShapeSetting case 4~8 에서 1:1 전사
- 매칭 함수·PDF 분석 확장은 다음 작업으로 분리(계약만 명시)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
배치면 초기설정의 자동 확정 스위치를 제거하고, PDF 분석으로 외벽선을 미확정
상태로 그린 직후 '외벽선 자동 확정' 팝업(스위치+확인)을 띄워 분기한다.
- ON: outerLineFix 확정 + saveCanvas 영속화 → 지붕형상 설정 직행
- OFF: 미확정 유지 → 외벽선 확정 팝업(WallLineSetting)
신규 메뉴 상수 AUTO_OUTERLINE_FIX + useMenu case 로 MenuDepth01 이 자동 표시
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
docs(outerline): 외벽선 확정(handleFix) 흐름 및 PDF 자동 확정 가이드 문서 추가
```
- 외벽선 확정 (`handleFix`) 로직의 상세 흐름과 확정 후 캔버스/Recoil 불변 조건을 문서화합니다.
- PDF 도면 분석을 통한 외벽선 자동 확정 기능 구현 시 참고할 설계 가이드와 체크리스트를 포함합니다.
- `handleFix` 본체와 `useEffect`, `ccwCheck` 등 관련 로직의 역할 및 주의사항을 명확히 합니다.
```
- usePdfImport.applyOuterline 에 autoFix 옵션 추가 — outerLineFix 확정 여부를 토글에 따라 분기
- PlacementShapeSetting.handleSaveBtn 에서 토글값으로 메뉴 분기(ON→ROOF_SHAPE_SETTINGS / OFF→EXTERIOR_WALL_LINE); 모달은 MenuDepth01 이 currentMenu 변화로 자동 오픈하므로 직접 addPopup 제거
- fix: basicSettingSave 의 setMenuByRoofSize 를 skipSideEffects 가드 안으로 이동 — ON 인데도 async 저장(await post) 직후 메뉴가 EXTERIOR_WALL_LINE 로 덮어써져 외벽선 작성 팝업으로 되돌아가며 확정이 풀리던 문제 수정
- docs(claude): PDF 임포트 절에 자동 확정 분기·MenuDepth01 메뉴 연동·skipSideEffects 주의 반영
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
배치면 초기설정 PDF 입력 화면에 '외벽선 자동 확정' 토글을 추가한다.
- autoOuterLineFixState 전역 atom 신설(기본값 true), outerLineFixState 와 별개의 옵션 플래그
- ko/ja i18n 라벨·설명 키 추가
- toggle-btn 스위치를 읽기 페이지 설정 행 아래 배치, 분석 중에는 비활성화
실제 PDF 자동 확정 동작 연결(usePdfImport)은 별도 작업으로 분리.
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
- '읽기 페이지 설정'의 평면도/입면도 페이지 번호가 프롬프트 힌트로만 쓰이고
PDF 전체가 Gemini 로 전송되던 문제 해결 — pdf-lib 로 지정 페이지만 잘라 전송
- 분할본이 12MB 이하면 inlineData(base64) 즉시 전송 → Files API 업로드·폴링 제거,
초과 시에만 Files API 로 fallback
- 분할 시 buildPrompt 를 페이지번호 힌트 대신 평면도/입면도 순서 매핑으로 전환
- 유효 페이지 0개 → 422 INVALID_PAGE_RANGE, 분할 실패 → 422 PDF_SPLIT_FAILED
- 설계 문서 추가(docs/superpowers/specs/2026-06-21-pdf-page-split-design.md)
Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
[작업내용] :
- 서버가 120,011ms 에 200 으로 정상 완료했는데 클라이언트 AbortController 가 정확히 120,000ms 에
fetch 를 끊어 타임아웃 toast 가 뜨던 문제 — gemini-3.1-pro-preview(thinking 비활성 불가)
+ MEDIA_RESOLUTION_HIGH PDF 분석은 정상 응답도 2분을 넘길 수 있어 300초로 확대
- 추후 진단용으로 서버에 단계별 소요시간(fileReady/generate) debug 로그 추가
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
[작업내용] :
- iron-session 세션 검사 추가 — 페이지용 layout redirect 가 API 라우트를 보호하지 않아
익명 요청으로 Gemini 과금이 가능하던 문제 차단(401)
- 사용자별 분당 5회 in-memory 레이트리밋(429) — 연타 업로드 과금 폭주 방지
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
[작업내용] :
- fitAndCenter 가 큰 도면(9.6m 초과)에 scale<1 을 좌표에 곱해 'QLine 길이×10=표시 mm' 불변식을
깨뜨리던 문제 해소 — 좌표는 실측 그대로 평행이동만 하는 centerOnCanvas 로 대체
- 화면맞춤은 fitViewport 로 분리: 캔버스 중앙 고정 viewportTransform 줌 + canvasZoomState 동기화
(useCanvasEvent 의 setZoom 은 동일 zoom 값에서 translation 을 보존)
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
[작업내용] :
- 진행 중인 PDF 분석 요청을 pdfRunRef 로 추적, 모달 언마운트 시 AbortController.abort() 호출
- fetch 완료 후·저신뢰 confirm 후 두 지점에서 컨트롤러 동일성 가드 — 언마운트로 무효화된 늦은 결과가
비워진 canvas 에 적용되고 saveCanvas 가 이전 플랜 DB 를 outline-only 로 덮어쓰던 데이터 손실 경로 차단
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
[작업내용] :
- useLine.addLine 경유로 outerLine 생성 — attributes/planeSize/fontSize 부여(지붕형상 설정·처마/케라바 편집·재로드 복원에 필수)
- canvas.outerLineFix + outerLineFixState 설정 — 미설정 시 지붕형상 설정 진입이 wall.line.not.found 로 즉시 차단되던 문제 해소
- skeletonBuilder 가 소비하는 outerLinePoint 정점 circle 생성(수동 플로우와 동일)
- 조기 WALL 폴리곤 생성 제거 — 수동 플로우와 동일하게 지붕형상 설정 적용 시점에 WALL/ROOF 생성
- 짧은엣지 dedup 을 '직전 유지 정점' 기준으로 수정하고 닫힘 엣지(Gemini 닫힌 링 반환 포함)까지 검사, 임계값을 addLine 의 1unit 과 일치
- PDF 적용 후 외벽선 그리기 메뉴(진입 시 재드로잉 강등) 대신 지붕형상 설정 메뉴로 직행
Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
- .agents/skills/grill-me/SKILL.md, skills-lock.json 추가
- CLAUDE.md 섹션 사이 빈 줄 보정 및 Always Do의 type check 항목 제거
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
LOW-PITCH-DIAG 진단 제거로 debugCapture 사용처가 0 이 되었고, 대상
/api/debug 라우트도 구현된 적이 없어 한 번도 동작하지 않던 죽은 코드다.
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
/api/debug 라우트가 구현된 적이 없어 debugCapture.log 호출이 매번 404 를
유발하던 콘솔 노이즈를 제거한다. 해당 진단은 주석에 "검증 후 제거"로 표시된
임시 코드였다(앱 동작에는 무영향).
- PlacementShapeSetting.jsx, useRoofAllocationSetting.js 에서 debugCapture
import 과 LOW-PITCH-DIAG 호출 3건 제거
- 진단 전용으로만 쓰이던 isLowPitchRestricted·LOW_PITCH_RESTRICTED_ROOF_IDS
import 도 함께 제거(notifyLowPitchRestrictionForRoofs 실기능 import 는 유지)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
finally 에서 await fileManager.deleteFile(...) 가 catch 의 return 을 게이팅해,
정리용 네트워크 호출이 행되면 500 응답조차 클라이언트로 송신되지 않던 문제를 해소한다.
- deleteFile 을 await 하지 않고 fire-and-forget + .catch 로 분리해 응답을 정리 완료에 묶지 않음
- 상주 Node 서버(PM2 next start)이므로 응답 후에도 detached 삭제가 정상 완료되며,
미삭제 시에도 Gemini 측에서 자동 만료
- 클라이언트 120s 타임아웃과 짝을 이뤄 한쪽이 행되어도 스피너에 갇히지 않음
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
PDF 분석 요청 실패/행(hang) 시 전역 스피너가 영구히 멈춰 화면 복귀가
불가능하던 문제를 해소한다.
- 네트워크 구간을 try/finally 로 감싸 성공·실패·타임아웃 어떤 경로든
스피너(pdfAnalyzing·isGlobalLoading)를 반드시 해제하도록 보장
- AbortController + 120s 타임아웃으로 무한 행 차단
- alert 은 스피너 해제 후 표시(스피너 z-index 가 alert 보다 높아 가려지는 것 방지)
- pdf.import.error.timeout 메시지 키 추가(ko/ja)
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
- analyzePdfAndApply에서 confidence < 0.6이면 반영 전 useSwal confirm으로 사용자 확인
- pdf.import.confirm.low.confidence 메시지 키 ko/ja 추가
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit introduces a new HTML document detailing the functionality of the PDF 도면 to 외벽선 자동작성 feature, including styles and layout for improved presentation.
- Adds a new `start:btob` script to `package.json` for launching the Next.js application on port 5060 for the BtoB environment.
- Introduces `startscript-btob.js` as a convenience executable to run the `start:btob` command.
- 「배치면 초기설정」 모달 寸法入力方法 라디오에 '도면 파일 업로드' 옵션 추가
- 선택 시 PDF 파일 업로드 + 읽기 페이지 설정(전체/입면도·평면도 지정) UI 노출
- 保存 클릭 시 /api/gemini/floor-plan 호출 → 외곽선을 캔버스에 반영한 후 기존 저장 흐름 진행
- Gemini File API 업로드 + finally 파일 폐기, 정점/면적 검증, 페이지 힌트 프롬프트 주입
- usePdfImport 훅: mm→canvas 좌표 변환, CCW 정규화, 기존 외곽선 덮어쓰기 confirm 후 QLine/QPolygon 생성
- @google/generative-ai 의존성 추가, GEMINI_MODEL env 4개 환경에 동기화
- 다국어(ja/ko) 메시지 추가, .playwright-mcp/ gitignore
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
[작업내용] :
- 대전제 반영: 케라바 ridge 가 생기는 분기에서 c1·c2 에 붙은 outer hip 2개 제거
· inner hip(junction 너머) 보존
· __removedHipsSnapshot 첨부 → revert 시 hip 2개 자동 복원
- revert 분기에서 hip 스냅샷 + ridge 스냅샷 둘 다 순회 복원하도록 대칭 보강
- 케라바 패턴 생성 라인 strokeWidth 2 → 4 (SK 라인과 동일, 6개소)
Integrates a PreToolUse hook that provides context from the 'graphify' knowledge graph.
When the AI is about to use search commands (e.g., `grep`, `find`, `ripgrep`),
it will be prompted to consult `GRAPH_REPORT.md` if a graph exists, guiding it to
leverage structured knowledge before searching raw files.
- .env.development / .env.production 에 GEMINI_API_KEY 추가 (PDF 평면도 분석 기능용)
- docs/ 에 PDF → Gemini → 캔버스 반영 기능 구현 계획서(html) 추가
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
5개 이미지 API 라우트(upload/cad/map/canvas/estimate-image-copy)의 서버 처리,
클라이언트 콜러(useRefFiles/useImgLoader/useEstimateController), S3 키 레이아웃,
캔버스 캡처 가드 조건과 알려진 거친 모서리를 한 문서에 정리.
Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>
- Stack / Scripts / Env / Routes / Source Layout / Deployment / Conventions / Troubleshooting 섹션을 현재 코드 상태(package.json, next.config.mjs, .env.*, ecosystem 파일) 기반으로 작성
- CLAUDE.md (gotcha 위주) 와 역할 분담: README 는 stack·디렉토리·env·배포 같은 기본 정보 담당
- docs/ PDF 와 .agents/skills/ 참조 인덱스 포함
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- README.md 가 사실상 create-next-app 보일러플레이트인데 "authoritative" 라고 안내하던 문구 교체 — 단일 진실 공급원이 CLAUDE.md + docs/ PDF 임을 명시
- graphify-out/ 디렉토리 부재 및 .gitignore 미등록 현실 반영, 28줄 가이드를 5줄 핵심 사용법으로 축소
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
closing edge 의 FP drift 누적(15mm/576mm ≈ 1.5°) 으로 가로/세로 라인이
기울어 보이는 문제. snapNearAxisEdges(angleTolDeg=2) 각도 기반 스냅을
4종 폴리곤(trestle/dormerTrestle/trestlePolygon/moduleSetupSurface) 에 적용.
- QPolygon.initialize name 가드: load/new 대부분 케이스 커버
- handleOuterlinesTest 끝 snap: trestlePolygon 은 makePolygon 후 .set 이라 별도
#1956 (vertical tilt, 2026-04-08) 의 horizontal 형제 케이스.
- .gitignore: .claude/** 차단 + settings.json·md negation 화이트리스트로 전환.
settings.local.json/projects·history·todos·cache 등 머신 전용 파일 누수 차단.
- .claude/settings.json: PreToolUse 훅 case 패턴을 첫 토큰 정확 매칭으로 교체.
*grep* 과매칭(egrep·git grep·grepl) 및 rg 단독 미매칭 문제 해소.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
- AGENTS.md alias 한 줄 추가 (Codex 등 타 에이전트 호환)
- .agents/skills 섹션 신설 — Vercel·Next.js 룰북 95개 위치/트리거 안내
- graphify-out 이 gitignore 된 로컬 캐시임 + 빈 상태 부트스트랩 방법 명시
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
gitignore 의 *.md / .claude/ 차단을 풀어 다음 파일을 git 으로 추적.
- /CLAUDE.md, /AGENTS.md (루트 에이전트 가이드)
- .agents/**/*.md (skills 문서 95개)
- .claude/settings.json (Claude Code 프로젝트 설정)
.claude/worktrees/ 는 git worktree 메타이므로 신규 ignore 라인으로 제외.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
graphify 지식 그래프 산출물(AST 캐시·graph.json·HTML·리포트)은 로컬 캐시이며
post-commit hook 으로 자동 갱신되므로 git 추적에서 제외.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
passivityCircuitAllocationRef (useRef) 선언 제거
원인: function component에 ref 전달 시 React warning 발생 (forwardRef 미사용)
PCS 접속함 응답에 추가된 moduleTpCd 필드를 Cross Mix 식별을 위해 프론트 상태 보존 및 getQuotationItem 제출 파라미터까지 흘려보내고, dedupe 키를 (itemId, moduleTpCd) 조합으로 변경.
passivityCircuitAllocationRef (useRef) 선언 제거
원인: function component에 ref 전달 시 React warning 발생 (forwardRef 미사용)
PCS 접속함 응답에 추가된 moduleTpCd 필드를 Cross Mix 식별을 위해 프론트 상태 보존 및 getQuotationItem 제출 파라미터까지 흘려보내고, dedupe 키를 (itemId, moduleTpCd) 조합으로 변경.
Parallel routes render multiple pages in the same layout. Intercepting routes show a different UI when navigating from within your app vs direct URL access. Together they enable modal patterns.
## File Structure
```
app/
├── @modal/ # Parallel route slot
│ ├── default.tsx # Required! Returns null
│ ├── (.)photos/ # Intercepts /photos/*
│ │ └── [id]/
│ │ └── page.tsx # Modal content
│ └── [...]catchall/ # Optional: catch unmatched
│ └── page.tsx
├── photos/
│ └── [id]/
│ └── page.tsx # Full page (direct access)
├── layout.tsx # Renders both children and @modal
└── page.tsx
```
## Step 1: Root Layout with Slot
```tsx
// app/layout.tsx
export default function RootLayout({
children,
modal,
}: {
children: React.ReactNode;
modal: React.ReactNode;
}) {
return (
<html>
<body>
{children}
{modal}
</body>
</html>
);
}
```
## Step 2: Default File (Critical!)
**Every parallel route slot MUST have a `default.tsx`** to prevent 404s on hard navigation.
```tsx
// app/@modal/default.tsx
export default function Default() {
return null;
}
```
Without this file, refreshing any page will 404 because Next.js can't determine what to render in the `@modal` slot.
## Step 3: Intercepting Route (Modal)
The `(.)` prefix intercepts routes at the same level.
```tsx
// app/@modal/(.)photos/[id]/page.tsx
import { Modal } from '@/components/modal';
export default async function PhotoModal({
params
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params;
const photo = await getPhoto(id);
return (
<Modal>
<imgsrc={photo.url}alt={photo.title}/>
</Modal>
);
}
```
## Step 4: Full Page (Direct Access)
```tsx
// app/photos/[id]/page.tsx
export default async function PhotoPage({
params
}: {
params: Promise<{ id: string }>
}) {
const { id } = await params;
const photo = await getPhoto(id);
return (
<divclassName="full-page">
<imgsrc={photo.url}alt={photo.title}/>
<h1>{photo.title}</h1>
</div>
);
}
```
## Step 5: Modal Component with Correct Closing
**Critical: Use `router.back()` to close modals, NOT `router.push()` or `<Link>`.**
```tsx
// components/modal.tsx
'use client';
import { useRouter } from 'next/navigation';
import { useCallback, useEffect, useRef } from 'react';
export function Modal({ children }: { children: React.ReactNode }) {
description: React and Next.js performance optimization guidelines from Vercel Engineering. This skill should be used when writing, reviewing, or refactoring React/Next.js code to ensure optimal performance patterns. Triggers on tasks involving React components, Next.js pages, data fetching, bundle optimization, or performance improvements.
license: MIT
metadata:
author: vercel
version: "1.0.0"
---
# Vercel React Best Practices
Comprehensive performance optimization guide for React and Next.js applications, maintained by Vercel. Contains 70 rules across 8 categories, prioritized by impact to guide automated refactoring and code generation.
## When to Apply
Reference these guidelines when:
- Writing new React components or Next.js pages
- Implementing data fetching (client or server-side)
Effect Event functions do not have a stable identity. Their identity intentionally changes on every render. Do not include the function returned by `useEffectEvent` in a `useEffect` dependency array. Keep the actual reactive values as dependencies and call the Effect Event from inside the effect body or subscriptions created by that effect.
**Incorrect (Effect Event added as a dependency):**
`useEffectEvent` provides a cleaner API for the same pattern: it creates a stable function reference that always calls the latest version of the handler.
Do not put app-wide initialization that must run once per app load inside `useEffect([])` of a component. Components can remount and effects will re-run. Use a module-level guard or top-level init in the entry module instead.
**Incorrect (runs twice in dev, re-runs on remount):**
```tsx
function Comp() {
useEffect(() => {
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
**Correct (once per app load):**
```tsx
let didInit = false
function Comp() {
useEffect(() => {
if (didInit) return
didInit = true
loadFromStorage()
checkAuthToken()
}, [])
// ...
}
```
Reference: [Initializing the application](https://react.dev/learn/you-might-not-need-an-effect#initializing-the-application)
When a branch uses `await` for a flag or remote value and also requires a **cheap synchronous** condition (local props, request metadata, already-loaded state), evaluate the cheap condition **first**. Otherwise you pay for the async call even when the compound condition can never be true.
This is a specialization of [Defer Await Until Needed](./async-defer-await.md) for `flag && cheapCondition` style checks.
**Incorrect:**
```typescript
const someFlag = await getFlag()
if (someFlag && someCondition) {
// ...
}
```
**Correct:**
```typescript
if (someCondition) {
const someFlag = await getFlag()
if (someFlag) {
// ...
}
}
```
This matters when `getFlag` hits the network, a feature-flag service, or `React.cache` / DB work: skipping it when `someCondition` is false removes that cost on the cold path.
Keep the original order if `someCondition` is expensive, depends on the flag, or you must run side effects in a fixed order.
This optimization is especially valuable when the skipped branch is frequently taken, or when the deferred operation is expensive.
For `await getFlag()` combined with a cheap synchronous guard (`flag && someCondition`), see [Check Cheap Conditions Before Async Flags](./async-cheap-condition-before-await.md).
Build tools work best when import and file-system paths are obvious at build time. If you hide the real path inside a variable or compose it too dynamically, the tool either has to include a broad set of possible files, warn that it cannot analyze the import, or widen file tracing to stay safe.
Prefer explicit maps or literal paths so the set of reachable files stays narrow and predictable. This is the same rule whether you are choosing modules with `import()` or reading files in server/build code.
When analysis becomes too broad, the cost is real:
- Larger server bundles
- Slower builds
- Worse cold starts
- More memory use
### Import Paths
**Incorrect (the bundler cannot tell what may be imported):**
```ts
const PAGE_MODULES = {
home: './pages/home',
settings: './pages/settings',
} as const
const Page = await import(PAGE_MODULES[pageName])
```
**Correct (use an explicit map of allowed modules):**
```ts
const PAGE_MODULES = {
home: () => import('./pages/home'),
settings: () => import('./pages/settings'),
} as const
const Page = await PAGE_MODULES[pageName]()
```
### File-System Paths
**Incorrect (a 2-value enum still hides the final path from static analysis):**
**Correct (make each final path literal at the callsite):**
```ts
const baseDir =
kind === ContentKind.Blog
? path.join(process.cwd(), 'content/blog')
: path.join(process.cwd(), 'content/docs')
```
In Next.js server code, this matters for output file tracing too. `path.join(process.cwd(), someVar)` can widen the traced file set because Next.js statically analyze `import`, `require`, and `fs` usage.
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 - Next.js 13.5+ (recommended):**
```js
// next.config.js - automatically optimizes barrel imports at build time
// Keep the standard imports - Next.js transforms them to direct imports
import { Check, X, Menu } from 'lucide-react'
// Full TypeScript support, no manual path wrangling
```
This is the recommended approach because it preserves TypeScript type safety and editor autocompletion while still eliminating the barrel import cost.
**Correct - Direct imports (non-Next.js projects):**
```tsx
import Button from '@mui/material/Button'
import TextField from '@mui/material/TextField'
// Loads only what you use
```
> **TypeScript warning:** Some libraries (notably `lucide-react`) don't ship `.d.ts` files for their deep import paths. Importing from `lucide-react/dist/esm/icons/check` resolves to an implicit `any` type, causing errors under `strict` or `noImplicitAny`. Prefer `optimizePackageImports` when available, or verify the library exports types for its subpaths before using direct imports.
These optimizations provide 15-70% faster dev boot, 28% faster builds, 40% faster cold starts, and significantly faster HMR.
// 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.
## Use Passive Event Listeners for Scrolling Performance
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.
Avoid interleaving style writes with layout reads. When you read a layout property (like `offsetWidth`, `getBoundingClientRect()`, or `getComputedStyle()`) between style changes, the browser is forced to trigger a synchronous reflow.
**This is OK (browser batches style changes):**
```typescript
function updateElementStyles(element: HTMLElement) {
// Each line invalidates style, but browser batches the recalculation
element.style.width = '100px'
element.style.height = '200px'
element.style.backgroundColor = 'blue'
element.style.border = '1px solid black'
}
```
**Incorrect (interleaved reads and writes force reflows):**
Prefer CSS classes over inline styles when possible. CSS files are cached by the browser, and classes provide better separation of concerns and are easier to maintain.
See [this gist](https://gist.github.com/paulirish/5d52fb081b3570c81e3a) and [CSS Triggers](https://csstriggers.com/) for more information on layout-forcing operations.
When comparing arrays with expensive operations (sorting, deep equality, serialization), check lengths first. If lengths differ, the arrays cannot be equal.
In real-world applications, this optimization is especially valuable when the comparison runs in hot paths (event handlers, render loops).
**Incorrect (always runs expensive comparison):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Always sorts and joins, even when lengths differ
Two O(n log n) sorts run even when `current.length` is 5 and `original.length` is 100. There is also overhead of joining the arrays and comparing the strings.
**Correct (O(1) length check first):**
```typescript
function hasChanges(current: string[], original: string[]) {
// Early return if lengths differ
if (current.length !== original.length) {
return true
}
// Only sort when lengths match
const currentSorted = current.toSorted()
const originalSorted = original.toSorted()
for (let i = 0; i <currentSorted.length;i++){
if (currentSorted[i] !== originalSorted[i]) {
return true
}
}
return false
}
```
This new approach is more efficient because:
- It avoids the overhead of sorting and joining the arrays when lengths differ
- It avoids consuming memory for the joined strings (especially important for large arrays)
if (projects[i].updatedAt <oldest.updatedAt)oldest =projects[i]
if (projects[i].updatedAt > newest.updatedAt) newest = projects[i]
}
return { oldest, newest }
}
```
Single pass through the array, no copying, no sorting.
**Alternative (Math.min/Math.max for small arrays):**
```typescript
const numbers = [5, 2, 8, 1, 9]
const min = Math.min(...numbers)
const max = Math.max(...numbers)
```
This works for small arrays, but can be slower or just throw an error for very large arrays due to spread operator limitations. Maximal array length is approximately 124000 in Chrome 143 and 638000 in Safari 18; exact numbers may vary - see [the fiddle](https://jsfiddle.net/qw1jabsx/4/). Use the loop approach for reliability.
## Defer Non-Critical Work with requestIdleCallback
**Impact: MEDIUM (keeps UI responsive during background tasks)**
Use `requestIdleCallback()` to schedule non-critical work during browser idle periods. This keeps the main thread free for user interactions and animations, reducing jank and improving perceived performance.
**Incorrect (blocks main thread during user interaction):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// These block the main thread immediately
analytics.track('search', { query })
saveToRecentSearches(query)
prefetchTopResults(results.slice(0, 3))
}
```
**Correct (defers non-critical work to idle time):**
```typescript
function handleSearch(query: string) {
const results = searchItems(query)
setResults(results)
// Defer non-critical work to idle periods
requestIdleCallback(() => {
analytics.track('search', { query })
})
requestIdleCallback(() => {
saveToRecentSearches(query)
})
requestIdleCallback(() => {
prefetchTopResults(results.slice(0, 3))
})
}
```
**With timeout for required work:**
```typescript
// Ensure analytics fires within 2 seconds even if browser stays busy
## Use toSorted() Instead of sort() for Immutability
`.sort()` mutates the array in place, which can cause bugs with React state and props. Use `.toSorted()` to create a new sorted array without mutation.
**Incorrect (mutates original array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Mutates the users prop array!
const sorted = useMemo(
() => users.sort((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Correct (creates new array):**
```typescript
function UserList({ users }: { users: User[] }) {
// Creates new sorted array, original unchanged
const sorted = useMemo(
() => users.toSorted((a, b) => a.name.localeCompare(b.name)),
[users]
)
return <div>{sorted.map(renderUser)}</div>
}
```
**Why this matters in React:**
1. Props/state mutations break React's immutability model - React expects props and state to be treated as read-only
2. Causes stale closure bugs - Mutating arrays inside closures (callbacks, effects) can lead to unexpected behavior
**Browser support (fallback for older browsers):**
`.toSorted()` is available in all modern browsers (Chrome 110+, Safari 16+, Firefox 115+, Node.js 20+). For older environments, use spread operator:
```typescript
// Fallback for older browsers
const sorted = [...items].sort((a, b) => a.value - b.value)
This applies to all CSS transforms and transitions (`transform`, `opacity`, `translate`, `scale`, `rotate`). The wrapper div allows browsers to use GPU acceleration for smoother animations.
Use explicit ternary operators (`? :`) instead of `&&` for conditional rendering when the condition can be `0`, `NaN`, or other falsy values that render.
**Incorrect (renders "0" when count is 0):**
```tsx
function Badge({ count }: { count: number }) {
return (
<div>
{count &&<spanclassName="badge">{count}</span>}
</div>
)
}
// When count = 0, renders: <div>0</div>
// When count = 5, renders: <div><spanclass="badge">5</span></div>
This is especially helpful for large and static SVG nodes, which can be expensive to recreate on every render.
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler automatically hoists static JSX elements and optimizes component re-renders, making manual hoisting unnecessary.
When rendering content that depends on client-side storage (localStorage, cookies), avoid both SSR breakage and post-hydration flickering by injecting a synchronous script that updates the DOM before React hydrates.
**Incorrect (breaks SSR):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
// localStorage is not available on server - throws error
Server-side rendering will fail because `localStorage` is undefined.
**Incorrect (visual flickering):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
const [theme, setTheme] = useState('light')
useEffect(() => {
// Runs after hydration - causes visible flash
const stored = localStorage.getItem('theme')
if (stored) {
setTheme(stored)
}
}, [])
return (
<divclassName={theme}>
{children}
</div>
)
}
```
Component first renders with default value (`light`), then updates after hydration, causing a visible flash of incorrect content.
**Correct (no flicker, no hydration mismatch):**
```tsx
function ThemeWrapper({ children }: { children: ReactNode }) {
return (
<>
<divid="theme-wrapper">
{children}
</div>
<script
dangerouslySetInnerHTML={{
__html: `
(function() {
try {
var theme = localStorage.getItem('theme') || 'light';
var el = document.getElementById('theme-wrapper');
if (el) el.className = theme;
} catch (e) {}
})();
`,
}}
/>
</>
)
}
```
The inline script executes synchronously before showing the element, ensuring the DOM already has the correct value. No flickering, no hydration mismatch.
This pattern is especially useful for theme toggles, user preferences, authentication states, and any client-only data that should render immediately without flashing default values.
impactDescription: avoids noisy hydration warnings for known differences
tags: rendering, hydration, ssr, nextjs
---
## Suppress Expected Hydration Mismatches
In SSR frameworks (e.g., Next.js), some values are intentionally different on server vs client (random IDs, dates, locale/timezone formatting). For these *expected* mismatches, wrap the dynamic text in an element with `suppressHydrationWarning` to prevent noisy warnings. Do not use this to hide real bugs. Don’t overuse it.
**Impact: HIGH (reduces load time for critical resources)**
React DOM provides APIs to hint the browser about resources it will need. These are especially useful in server components to start loading resources before the client even receives the HTML.
- **`prefetchDNS(href)`**: Resolve DNS for a domain you expect to connect to
- **`preconnect(href)`**: Establish connection (DNS + TCP + TLS) to a server
- **`preload(href, options)`**: Fetch a resource (stylesheet, font, script, image) you'll use soon
- **`preloadModule(href)`**: Fetch an ES module you'll use soon
- **`preinit(href, options)`**: Fetch and evaluate a stylesheet or script
- **`preinitModule(href)`**: Fetch and evaluate an ES module
**Example (preconnect to third-party APIs):**
```tsx
import { preconnect, prefetchDNS } from 'react-dom'
export default function App() {
prefetchDNS('https://analytics.example.com')
preconnect('https://api.example.com')
return <main>{/* content */}</main>
}
```
**Example (preload critical fonts and styles):**
```tsx
import { preload, preinit } from 'react-dom'
export default function RootLayout({ children }) {
Script tags without `defer` or `async` block HTML parsing while the script downloads and executes. This delays First Contentful Paint and Time to Interactive.
- **`defer`**: Downloads in parallel, executes after HTML parsing completes, maintains execution order
- **`async`**: Downloads in parallel, executes immediately when ready, no guaranteed order
Use `defer` for scripts that depend on DOM or other scripts. Use `async` for independent scripts like analytics.
Reduce SVG coordinate precision to decrease file size. The optimal precision depends on the viewBox size, but in general reducing precision should be considered.
**Incorrect (excessive precision):**
```svg
<pathd="M 10.293847 20.847362 L 30.938472 40.192837"/>
impactDescription: avoids redundant renders and state drift
tags: rerender, derived-state, useEffect, state
---
## Calculate Derived State During Rendering
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.
When updating state based on the current state value, use the functional update form of setState instead of directly referencing the state variable. This prevents stale closures, eliminates unnecessary dependencies, and creates stable callback references.
**Incorrect (requires state as dependency):**
```tsx
function TodoList() {
const [items, setItems] = useState(initialItems)
// Callback must depend on items, recreated on every items change
The first callback is recreated every time `items` changes, which can cause child components to re-render unnecessarily. The second callback has a stale closure bug—it will always reference the initial `items` value.
**Correct (stable callbacks, no stale closures):**
4. **Prevents bugs** - Eliminates the most common source of React closure bugs
**When to use functional updates:**
- Any setState that depends on the current state value
- Inside useCallback/useMemo when state is needed
- Event handlers that reference state
- Async operations that update state
**When direct updates are fine:**
- Setting state to a static value: `setCount(0)`
- Setting state from props/arguments only: `setName(newName)`
- State doesn't depend on previous value
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, the compiler can automatically optimize some cases, but functional updates are still recommended for correctness and to prevent stale closure bugs.
Pass a function to `useState` for expensive initial values. Without the function form, the initializer runs on every render even though the value is only used once.
**Incorrect (runs on every render):**
```tsx
function FilteredList({ items }: { items: Item[] }) {
// buildSearchIndex() runs on EVERY render, even after initialization
Use lazy initialization when computing initial values from localStorage/sessionStorage, building data structures (indexes, maps), reading from the DOM, or performing heavy transformations.
For simple primitives (`useState(0)`), direct references (`useState(props.value)`), or cheap literals (`useState({})`), the function form is unnecessary.
title: Extract Default Non-primitive Parameter Value from Memoized Component to Constant
impact: MEDIUM
impactDescription: restores memoization by using a constant for default value
tags: rerender, memo, optimization
---
## Extract Default Non-primitive Parameter Value from Memoized Component to Constant
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):**
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 <Avatarid={id}/>
}, [user])
if (loading) return <Skeleton/>
return <div>{avatar}</div>
}
```
**Correct (skips computation when loading):**
```tsx
const UserAvatar = memo(function UserAvatar({ user }: { user: User }) {
const id = useMemo(() => computeAvatarId(user), [user])
return <Avatarid={id}/>
})
function Profile({ user, loading }: Props) {
if (loading) return <Skeleton/>
return (
<div>
<UserAvataruser={user}/>
</div>
)
}
```
**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.
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.
Reference: [Should this code move to an event handler?](https://react.dev/learn/removing-effect-dependencies#should-this-code-move-to-an-event-handler)
impactDescription: prevents remount on every render
tags: rerender, components, remount, performance
---
## Don't Define Components Inside Components
**Impact: HIGH (prevents remount on every render)**
Defining a component inside another component creates a new component type on every render. React sees a different component each time and fully remounts it, destroying all state and DOM.
A common reason developers do this is to access parent variables without passing props. Always pass props instead.
Every time `UserProfile` renders, `Avatar` and `Stats` are new component types. React unmounts the old instances and mounts new ones, losing any internal state, running effects again, and recreating DOM nodes.
title: Do not wrap a simple expression with a primitive result type in useMemo
impact: LOW-MEDIUM
impactDescription: wasted computation on every render
tags: rerender, useMemo, optimization
---
## Do not wrap a simple expression with a primitive result type in useMemo
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.
When a hook contains multiple independent tasks with different dependencies, split them into separate hooks. A combined hook reruns all tasks when any dependency changes, even if some tasks don't use the changed value.
This pattern also applies to `useEffect` when combining unrelated side effects:
**Incorrect (both effects run when either dependency changes):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
document.title = `${pageTitle} | My App`
}, [pathname, pageTitle])
```
**Correct (effects run independently):**
```tsx
useEffect(() => {
analytics.trackPageView(pathname)
}, [pathname])
useEffect(() => {
document.title = `${pageTitle} | My App`
}, [pageTitle])
```
**Note:** If your project has [React Compiler](https://react.dev/learn/react-compiler) enabled, it automatically optimizes dependency tracking and may handle some of these cases for you.
## Use useDeferredValue for Expensive Derived Renders
When user input triggers expensive computations or renders, use `useDeferredValue` to keep the input responsive. The deferred value lags behind, allowing React to prioritize the input update and render the expensive result when idle.
**Incorrect (input feels laggy while filtering):**
impactDescription: avoids unnecessary re-renders on frequent updates
tags: rerender, useref, state, performance
---
## Use useRef for Transient Values
When a value changes frequently and you don't want a re-render on every update (e.g., mouse trackers, intervals, transient flags), store it in `useRef` instead of `useState`. Keep component state for UI; use refs for temporary DOM-adjacent values. Updating a ref does not trigger a re-render.
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.
**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) {
`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<string,any>({
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.
If you must pass objects, pass the same reference:
```typescript
const params = { uid: 1 }
getUser(params) // Query runs
getUser(params) // Cache hit (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.
**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.
**Impact: HIGH (avoids repeated file/network I/O per request)**
When loading static assets (fonts, logos, images, config files) in route handlers or server functions, hoist the I/O operation to module level. Module-level code runs once when the module is first imported, not on every request. This eliminates redundant file system reads or network fetches that would otherwise run on every invocation.
**Incorrect (reads font file on every request):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
export async function GET(request: Request) {
// Runs on EVERY request - expensive!
const fontData = await fetch(
new URL('./fonts/Inter.ttf', import.meta.url)
).then(res => res.arrayBuffer())
const logoData = await fetch(
new URL('./images/logo.png', import.meta.url)
).then(res => res.arrayBuffer())
return new ImageResponse(
<divstyle={{fontFamily:'Inter'}}>
<imgsrc={logoData}/>
Hello World
</div>,
{ fonts: [{ name: 'Inter', data: fontData }] }
)
}
```
**Correct (loads once at module initialization):**
```typescript
// app/api/og/route.tsx
import { ImageResponse } from 'next/og'
// Module-level: runs ONCE when module is first imported
export async function processRequest(data: Data) {
const [config, template] = await Promise.all([
configPromise,
templatePromise,
])
return render(template, data, config)
}
```
When to use this pattern:
- Loading fonts for OG image generation
- Loading static logos, icons, or watermarks
- Reading configuration files that don't change at runtime
- Loading email templates or other static templates
- Any static asset that's the same across all requests
When not to use this pattern:
- Assets that vary per request or user
- Files that may change during runtime (use caching with TTL instead)
- Large files that would consume too much memory if kept loaded
- Sensitive data that shouldn't persist in memory
With Vercel's [Fluid Compute](https://vercel.com/docs/fluid-compute), module-level caching is especially effective because multiple concurrent requests share the same function instance. The static assets stay loaded in memory across requests without cold start penalties.
In traditional serverless, each cold start re-executes module-level code, but subsequent warm invocations reuse the loaded assets until the instance is recycled.
impactDescription: prevents concurrency bugs and request data leaks
tags: server, rsc, ssr, concurrency, security, state
---
## Avoid Shared Module State for Request Data
For React Server Components and client components rendered during SSR, avoid using mutable module-level variables to share request-scoped data. Server renders can run concurrently in the same process. If one render writes to shared module state and another render reads it, you can get race conditions, cross-request contamination, and security bugs where one user's data appears in another user's response.
Treat module scope on the server as process-wide shared memory, not request-local state.
**Incorrect (request data leaks across concurrent renders):**
```tsx
let currentUser: User | null = null
export default async function Page() {
currentUser = await auth()
return <Dashboard/>
}
async function Dashboard() {
return <div>{currentUser?.name}</div>
}
```
If two requests overlap, request A can set `currentUser`, then request B overwrites it before request A finishes rendering `Dashboard`.
**Correct (keep request data local to the render tree):**
```tsx
export default async function Page() {
const user = await auth()
return <Dashboarduser={user}/>
}
function Dashboard({ user }: { user: User | null }) {
return <div>{user?.name}</div>
}
```
Safe exceptions:
- Immutable static assets or config loaded once at module scope
- Shared caches intentionally designed for cross-request reuse and keyed correctly
- Process-wide singletons that do not store request- or user-specific mutable data
For static assets and config, see [Hoist Static I/O to Module Level](./server-hoist-static-io.md).
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.
"command":"CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); set -- $CMD; case \"$1\" in grep|egrep|fgrep|rg|ripgrep|find|fd|ack|ag) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}' || true ;; esac"
"command":"CMD=$(python3 -c \"import json,sys; d=json.load(sys.stdin); print(d.get('tool_input',d).get('command',''))\" 2>/dev/null || true); set -- $CMD; case \"$1\" in grep|egrep|fgrep|rg|ripgrep|find|fd|ack|ag) [ -f graphify-out/graph.json ] && echo '{\"hookSpecificOutput\":{\"hookEventName\":\"PreToolUse\",\"additionalContext\":\"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files.\"}}' || true ;; esac"
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.