프론트엔드 개발 가이드라인
목적
React 19를 사용한 최신 Next.js 15 개발을 위한 종합 가이드로, Server Components, Client Components, App Router 패턴, Shadcn/ui 컴포넌트, 적절한 파일 구성 및 성능 최적화에 중점을 둡니다.
이 스킬을 사용해야 할 때
- 새 컴포넌트나 페이지 생성
- 새로운 기능 구축
- 데이터 가져오기 (Server Components, Server Actions)
- Next.js App Router로 라우팅 설정
- Tailwind CSS 및 Shadcn/ui로 컴포넌트 스타일링
- 성능 최적화
- 프론트엔드 코드 구성
- TypeScript 모범 사례
빠른 시작
새 컴포넌트 점검표
컴포넌트를 만드시나요? 다음 점검표를 따르세요:
- Server vs Client Component 결정 (기본값: Server Component)
- 필요한 경우에만
"use client"지시문 추가 (상호작용, 훅, 브라우저 API) - 명시적인 prop 타입과 함께 TypeScript 사용
-
@/components/ui에서 Shadcn/ui 컴포넌트 가져오기 - 스타일링에 Tailwind CSS 클래스 사용
- Import alias 사용:
@/components,@/lib,@/hooks - 조건부 클래스에
cn()유틸리티 사용 - 기본 내보내기는 파일 하단에
- 가능할 때 데이터 가져오기에 Server Components 사용
새 페이지 점검표
페이지를 만드시나요? 다음 구조를 설정하세요:
- 경로를 위해
app/{route-name}/page.tsx생성 - 기본적으로 Server Component 사용
- Server Component에서 직접 데이터 가져오기
- 페이지별 컴포넌트를 위한
components/디렉토리 생성 - 로딩 상태를 위해
loading.tsx사용 - 오류 경계를 위해
error.tsx사용 - SEO를 위해 메타데이터 내보내기
Import Alias 빠른 참조
| Alias | 해석 대상 | 예시 |
|---|---|---|
@/ | 프로젝트 루트 | import { cn } from '@/lib/utils' |
@/components | components/ | import { Button } from '@/components/ui/button' |
@/lib | lib/ | import { cn } from '@/lib/utils' |
@/hooks | hooks/ | import { useMobile } from '@/hooks/use-mobile' |
@/app | app/ | import { Metadata } from 'next' |
tsconfig.json 경로 구성에 정의됨
일반 Import 치트시트
// Next.js
import { Metadata } from 'next'
import { Suspense } from 'react'
import { notFound, redirect } from 'next/navigation'
// React (Client Components 전용)
;('use client')
import { useState, useCallback, useMemo } from 'react'
// Shadcn/ui 컴포넌트
import { Button } from '@/components/ui/button'
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import { Input } from '@/components/ui/input'
// 유틸리티
import { cn } from '@/lib/utils'
// 훅 (Client Components 전용)
import { useMobile } from '@/hooks/use-mobile'
// 타입
import type { ComponentProps } from 'react'
주제 가이드
🎨 컴포넌트 패턴
Server Components vs Client Components:
- Server Components (기본값):
"use client"없음, 데이터 직접 가져오기 가능, 번들 크기 감소 - Client Components: 상호작용, 훅, 브라우저 API를 위해
"use client"추가
핵심 개념:
- 기본적으로 Server Components 사용
- 필요한 경우에만 Client Components 사용
- Shadcn/ui 컴포넌트 사용 (이미 Client Components)
- 컴포넌트 구조: Props → 데이터 가져오기 → 렌더링 → 내보내기
예시 Server Component:
// app/features/posts/components/PostList.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
interface PostListProps {
posts: Post[]
}
export function PostList({ posts }: PostListProps) {
return (
<div className='grid gap-4'>
{posts.map((post) => (
<Card key={post.id}>
<CardHeader>
<CardTitle>{post.title}</CardTitle>
</CardHeader>
<CardContent>{post.content}</CardContent>
</Card>
))}
</div>
)
}
예시 Client Component:
// app/features/posts/components/PostForm.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
export function PostForm() {
const [title, setTitle] = useState('')
return (
<form>
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
<Button type='submit'>Submit</Button>
</form>
)
}
📊 데이터 가져오기
기본 패턴: Server Components
- Server Components에서 직접 데이터 가져오기
- Server Components에서
async/await사용 useEffect나 데이터 가져오기 라이브러리 불필요- 자동 요청 중복 제거
Server Actions:
- 변형(폼, 업데이트)에 사용
app/actions/디렉토리 생성"use server"지시문 표시
데이터 가져오기가 포함된 Server Component 예시:
// app/posts/page.tsx
import { PostList } from '@/components/PostList'
async function getPosts() {
const res = await fetch('https://api.example.com/posts', {
cache: 'no-store', // 또는 'force-cache', 'revalidate'
})
return res.json()
}
export default async function PostsPage() {
const posts = await getPosts()
return <PostList posts={posts} />
}
Server Action 예시:
// app/actions/posts.ts
'use server'
export async function createPost(formData: FormData) {
const title = formData.get('title')
// ... 유효성 검사 및 생성 로직
redirect('/posts')
}
📁 파일 구성
App Router 구조:
app/
(routes)/
page.tsx # 경로 페이지
layout.tsx # 경로 레이아웃
loading.tsx # 로딩 UI
error.tsx # 오류 UI
components/ # 공유 컴포넌트
ui/ # Shadcn/ui 컴포넌트
features/ # 기능별 코드
posts/
components/ # 기능 컴포넌트
actions/ # Server Actions
types/ # TypeScript 타입
lib/
utils.ts # 유틸리티 (cn 등)
hooks/
use-mobile.ts # 커스텀 훅 (Client 전용)
기능 구성:
app/features/{feature}/: 기능별 페이지/경로components/: 진정한 재사용 가능한 컴포넌트components/ui/: Shadcn/ui 컴포넌트 (직접 수정하지 않음)
🎨 스타일링
Tailwind CSS + Shadcn/ui:
- Tailwind 유틸리티 클래스 사용
- 조건부 클래스에
cn()유틸리티 사용 - Shadcn/ui 컴포넌트는 CSS 변수로 테마 지정
app/globals.css에서 테마 커스터마이즈
스타일링 패턴:
import { cn } from '@/lib/utils'
interface ButtonProps {
variant?: 'primary' | 'secondary'
className?: string
}
export function Button({ variant = 'primary', className }: ButtonProps) {
return (
<button
className={cn(
'rounded-md px-4 py-2',
variant === 'primary' && 'bg-primary text-primary-foreground',
variant === 'secondary' && 'bg-secondary text-secondary-foreground',
className,
)}
>
Click me
</button>
)
}
Shadcn/ui 컴포넌트:
@/components/ui/{component-name}에서 가져오기- 컴포넌트는 이미 스타일링되고 접근성이 확보됨
classNameprop 또는 CSS 변수로 커스터마이즈
🛣️ 라우팅
Next.js App Router - 파일 기반:
- 디렉토리:
app/{route-name}/page.tsx - 중첩 경로:
app/{parent}/{child}/page.tsx - 동적 경로:
app/posts/[id]/page.tsx - 경로 그룹:
app/(marketing)/about/page.tsx
경로 예시:
// app/posts/page.tsx
import { Metadata } from 'next'
import { PostList } from '@/components/PostList'
export const metadata: Metadata = {
title: 'Posts',
description: '모든 게시물 목록',
}
export default async function PostsPage() {
const posts = await getPosts()
return (
<div className='container mx-auto py-8'>
<h1 className='text-3xl font-bold mb-6'>Posts</h1>
<PostList posts={posts} />
</div>
)
}
동적 경로:
// app/posts/[id]/page.tsx
interface PostPageProps {
params: Promise<{ id: string }>
}
export default async function PostPage({ params }: PostPageProps) {
const { id } = await params
const post = await getPost(id)
if (!post) {
notFound()
}
return <PostDetail post={post} />
}
⏳ 로딩 및 오류 상태
로딩 상태:
- 경로 디렉토리에
loading.tsx생성 - 자동으로 페이지를 Suspense로 감쌈
- 경로 수준 로딩에 사용
오류 경계:
- 경로 디렉토리에
error.tsx생성 - 경로에서 오류를 자동으로 잡음
- 오류 상태를 재설정할 수 있음
로딩 UI 예시:
// app/posts/loading.tsx
export default function Loading() {
return (
<div className='flex items-center justify-center min-h-screen'>
<div className='animate-spin rounded-full h-8 w-8 border-b-2 border-primary' />
</div>
)
}
오류 UI 예시:
// app/posts/error.tsx
'use client'
import { useEffect } from 'react'
import { Button } from '@/components/ui/button'
export default function Error({
error,
reset,
}: {
error: Error & { digest?: string }
reset: () => void
}) {
useEffect(() => {
console.error(error)
}, [error])
return (
<div className='flex flex-col items-center justify-center min-h-screen'>
<h2 className='text-2xl font-bold mb-4'>문제가 발생했습니다!</h2>
<Button onClick={reset}>다시 시도</Button>
</div>
)
}
⚡ 성능
최적화 패턴:
- Server Components 사용 (번들 크기 감소)
- 이미지에
next/image사용 - 폰트에
next/font사용 - 가능할 때 Client Components 지연 로딩
- Client Components에서
useMemo와useCallback사용 - Suspense 경계로 데이터 스트리밍
이미지 최적화:
import Image from 'next/image'
export function Avatar({ src, alt }: { src: string; alt: string }) {
return (
<Image
src={src}
alt={alt}
width={40}
height={40}
className='rounded-full'
/>
)
}
Suspense로 스트리밍:
import { Suspense } from 'react'
import { PostList } from '@/components/PostList'
import { Loading } from '@/components/Loading'
export default function Page() {
return (
<div>
<Suspense fallback={<Loading />}>
<PostList />
</Suspense>
</div>
)
}
📘 TypeScript
표준:
- Strict 모드 활성화
any타입 금지- 함수에 명시적 반환 타입
- 타입 가져오기:
import type { Post } from '@/types/post' - JSDoc이 포함된 컴포넌트 prop 인터페이스
예시:
import type { ComponentProps } from 'react'
import { Button } from '@/components/ui/button'
/**
* 로딩 상태가 포함된 커스텀 버튼 컴포넌트
*/
interface CustomButtonProps extends ComponentProps<typeof Button> {
isLoading?: boolean
}
export function CustomButton({
isLoading,
children,
...props
}: CustomButtonProps) {
return (
<Button disabled={isLoading} {...props}>
{isLoading ? '로딩 중...' : children}
</Button>
)
}
🔧 일반적인 패턴
폼 처리:
- 폼 제출에 Server Actions 사용
- 유효성 검사에
react-hook-form과zod사용 (Client Components) - Shadcn/ui Form 컴포넌트 사용
Server Action을 사용한 폼 예시:
// app/actions/posts.ts
'use server'
import { z } from 'zod'
const createPostSchema = z.object({
title: z.string().min(1),
content: z.string().min(1),
})
export async function createPost(formData: FormData) {
const rawData = {
title: formData.get('title'),
content: formData.get('content'),
}
const validated = createPostSchema.parse(rawData)
// ... 게시물 생성 로직
redirect('/posts')
}
메타데이터:
import { Metadata } from 'next'
export const metadata: Metadata = {
title: 'Posts',
description: '모든 게시물 목록',
openGraph: {
title: 'Posts',
description: '모든 게시물 목록',
},
}
핵심 원칙
- Server Components 우선: 기본적으로 Server Components를 사용하고, 필요한 경우에만 Client Components를 사용합니다.
- App Router 구조:
app/디렉토리와 파일 기반 라우팅을 사용합니다. - Shadcn/ui 컴포넌트: 사전 구축된 접근성 높은 컴포넌트를 사용합니다.
- Tailwind CSS:
cn()헬퍼와 함께 유틸리티 우선 스타일링을 사용합니다. - TypeScript Strict:
any금지, 명시적 타입을 사용합니다. - 성능: Server Components를 사용하고, 이미지를 최적화하며, 필요 시 지연 로딩을 사용합니다.
- 파일 구성: 기능은
app/features/, 공유는components/에 배치합니다. - Import Alias: 깔끔한 import를 위해
@/접두사를 사용합니다.
빠른 참조: 파일 구조
app/
layout.tsx # 루트 레이아웃
page.tsx # 홈 페이지
globals.css # 전역 스타일
(routes)/
posts/
page.tsx # 게시물 목록 페이지
[id]/
page.tsx # 게시물 상세 페이지
loading.tsx # 로딩 UI
error.tsx # 오류 UI
features/
posts/
components/
PostList.tsx # 기능 컴포넌트
actions/
posts.ts # Server Actions
components/
ui/ # Shadcn/ui 컴포넌트
button.tsx
card.tsx
lib/
utils.ts # 유틸리티 (cn 등)
hooks/
use-mobile.ts # 커스텀 훅
모던 컴포넌트 템플릿 (빠른 복사)
Server Component:
// app/components/PostCard.tsx
import { Card, CardHeader, CardTitle, CardContent } from '@/components/ui/card'
import type { Post } from '@/types/post'
interface PostCardProps {
post: Post
}
export function PostCard({ post }: PostCardProps) {
return (
<Card>
<CardHeader>
<CardTitle>{post.title}</CardTitle>
</CardHeader>
<CardContent>
<p>{post.content}</p>
</CardContent>
</Card>
)
}
Client Component:
// app/components/PostForm.tsx
'use client'
import { useState } from 'react'
import { Button } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
export function PostForm() {
const [title, setTitle] = useState('')
return (
<form>
<Input value={title} onChange={(e) => setTitle(e.target.value)} />
<Button type='submit'>제출</Button>
</form>
)
}