--- name: frontend-patterns description: React, Next.js, 상태 관리, 성능 최적화 및 UI 모범 사례를 위한 프론트엔드 개발 패턴. origin: ECC --- # 프론트엔드 개발 패턴 React, Next.js 및 고성능 사용자 인터페이스를 위한 모던 프론트엔드 패턴. ## 활성화 시점 - React 컴포넌트를 구축할 때 (합성, props, 렌더링) - 상태를 관리할 때 (useState, useReducer, Zustand, Context) - 데이터 페칭을 구현할 때 (SWR, React Query, server components) - 성능을 최적화할 때 (메모이제이션, 가상화, 코드 분할) - 폼을 다룰 때 (유효성 검사, 제어 입력, Zod 스키마) - 클라이언트 사이드 라우팅과 네비게이션을 처리할 때 - 접근성 있고 반응형인 UI 패턴을 구축할 때 ## 컴포넌트 패턴 ### 상속보다 합성 ```typescript // PASS: GOOD: Component composition interface CardProps { children: React.ReactNode variant?: 'default' | 'outlined' } export function Card({ children, variant = 'default' }: CardProps) { return
{children}
} export function CardHeader({ children }: { children: React.ReactNode }) { return
{children}
} export function CardBody({ children }: { children: React.ReactNode }) { return
{children}
} // Usage Title Content ``` ### Compound Components ```typescript interface TabsContextValue { activeTab: string setActiveTab: (tab: string) => void } const TabsContext = createContext(undefined) export function Tabs({ children, defaultTab }: { children: React.ReactNode defaultTab: string }) { const [activeTab, setActiveTab] = useState(defaultTab) return ( {children} ) } export function TabList({ children }: { children: React.ReactNode }) { return
{children}
} export function Tab({ id, children }: { id: string, children: React.ReactNode }) { const context = useContext(TabsContext) if (!context) throw new Error('Tab must be used within Tabs') return ( ) } // Usage Overview Details ``` ### Render Props 패턴 ```typescript interface DataLoaderProps { url: string children: (data: T | null, loading: boolean, error: Error | null) => React.ReactNode } export function DataLoader({ url, children }: DataLoaderProps) { const [data, setData] = useState(null) const [loading, setLoading] = useState(true) const [error, setError] = useState(null) useEffect(() => { fetch(url) .then(res => res.json()) .then(setData) .catch(setError) .finally(() => setLoading(false)) }, [url]) return <>{children(data, loading, error)} } // Usage url="/api/markets"> {(markets, loading, error) => { if (loading) return if (error) return return }} ``` ## 커스텀 Hook 패턴 ### 상태 관리 Hook ```typescript export function useToggle(initialValue = false): [boolean, () => void] { const [value, setValue] = useState(initialValue) const toggle = useCallback(() => { setValue(v => !v) }, []) return [value, toggle] } // Usage const [isOpen, toggleOpen] = useToggle() ``` ### 비동기 데이터 페칭 Hook ```typescript import { useCallback, useEffect, useRef, useState } from 'react' interface UseQueryOptions { onSuccess?: (data: T) => void onError?: (error: Error) => void enabled?: boolean } export function useQuery( key: string, fetcher: () => Promise, options?: UseQueryOptions ) { const [data, setData] = useState(null) const [error, setError] = useState(null) const [loading, setLoading] = useState(false) const successRef = useRef(options?.onSuccess) const errorRef = useRef(options?.onError) const enabled = options?.enabled !== false useEffect(() => { successRef.current = options?.onSuccess errorRef.current = options?.onError }, [options?.onSuccess, options?.onError]) const refetch = useCallback(async () => { setLoading(true) setError(null) try { const result = await fetcher() setData(result) successRef.current?.(result) } catch (err) { const error = err as Error setError(error) errorRef.current?.(error) } finally { setLoading(false) } }, [fetcher]) useEffect(() => { if (enabled) { refetch() } }, [key, enabled, refetch]) return { data, error, loading, refetch } } // Usage const { data: markets, loading, error, refetch } = useQuery( 'markets', () => fetch('/api/markets').then(r => r.json()), { onSuccess: data => console.log('Fetched', data.length, 'markets'), onError: err => console.error('Failed:', err) } ) ``` ### Debounce Hook ```typescript export function useDebounce(value: T, delay: number): T { const [debouncedValue, setDebouncedValue] = useState(value) useEffect(() => { const handler = setTimeout(() => { setDebouncedValue(value) }, delay) return () => clearTimeout(handler) }, [value, delay]) return debouncedValue } // Usage const [searchQuery, setSearchQuery] = useState('') const debouncedQuery = useDebounce(searchQuery, 500) useEffect(() => { if (debouncedQuery) { performSearch(debouncedQuery) } }, [debouncedQuery]) ``` ## 상태 관리 패턴 ### Context + Reducer 패턴 ```typescript interface State { markets: Market[] selectedMarket: Market | null loading: boolean } type Action = | { type: 'SET_MARKETS'; payload: Market[] } | { type: 'SELECT_MARKET'; payload: Market } | { type: 'SET_LOADING'; payload: boolean } function reducer(state: State, action: Action): State { switch (action.type) { case 'SET_MARKETS': return { ...state, markets: action.payload } case 'SELECT_MARKET': return { ...state, selectedMarket: action.payload } case 'SET_LOADING': return { ...state, loading: action.payload } default: return state } } const MarketContext = createContext<{ state: State dispatch: Dispatch } | undefined>(undefined) export function MarketProvider({ children }: { children: React.ReactNode }) { const [state, dispatch] = useReducer(reducer, { markets: [], selectedMarket: null, loading: false }) return ( {children} ) } export function useMarkets() { const context = useContext(MarketContext) if (!context) throw new Error('useMarkets must be used within MarketProvider') return context } ``` ## 성능 최적화 ### 메모이제이션 ```typescript // PASS: useMemo for expensive computations const sortedMarkets = useMemo(() => { return [...markets].sort((a, b) => b.volume - a.volume) }, [markets]) // PASS: useCallback for functions passed to children const handleSearch = useCallback((query: string) => { setSearchQuery(query) }, []) // PASS: React.memo for pure components export const MarketCard = React.memo(({ market }) => { return (

{market.name}

{market.description}

) }) ``` ### 코드 분할 및 지연 로딩 ```typescript import { lazy, Suspense } from 'react' // PASS: Lazy load heavy components const HeavyChart = lazy(() => import('./HeavyChart')) const ThreeJsBackground = lazy(() => import('./ThreeJsBackground')) export function Dashboard() { return (
}>
) } ``` ### 긴 리스트를 위한 가상화 ```typescript import { useVirtualizer } from '@tanstack/react-virtual' export function VirtualMarketList({ markets }: { markets: Market[] }) { const parentRef = useRef(null) const virtualizer = useVirtualizer({ count: markets.length, getScrollElement: () => parentRef.current, estimateSize: () => 100, // Estimated row height overscan: 5 // Extra items to render }) return (
{virtualizer.getVirtualItems().map(virtualRow => (
))}
) } ``` ## 폼 처리 패턴 ### 유효성 검사가 포함된 제어 폼 ```typescript interface FormData { name: string description: string endDate: string } interface FormErrors { name?: string description?: string endDate?: string } export function CreateMarketForm() { const [formData, setFormData] = useState({ name: '', description: '', endDate: '' }) const [errors, setErrors] = useState({}) const validate = (): boolean => { const newErrors: FormErrors = {} if (!formData.name.trim()) { newErrors.name = 'Name is required' } else if (formData.name.length > 200) { newErrors.name = 'Name must be under 200 characters' } if (!formData.description.trim()) { newErrors.description = 'Description is required' } if (!formData.endDate) { newErrors.endDate = 'End date is required' } setErrors(newErrors) return Object.keys(newErrors).length === 0 } const handleSubmit = async (e: React.FormEvent) => { e.preventDefault() if (!validate()) return try { await createMarket(formData) // Success handling } catch (error) { // Error handling } } return (
setFormData(prev => ({ ...prev, name: e.target.value }))} placeholder="Market name" /> {errors.name && {errors.name}} {/* Other fields */}
) } ``` ## Error Boundary 패턴 ```typescript interface ErrorBoundaryState { hasError: boolean error: Error | null } export class ErrorBoundary extends React.Component< { children: React.ReactNode }, ErrorBoundaryState > { state: ErrorBoundaryState = { hasError: false, error: null } static getDerivedStateFromError(error: Error): ErrorBoundaryState { return { hasError: true, error } } componentDidCatch(error: Error, errorInfo: React.ErrorInfo) { console.error('Error boundary caught:', error, errorInfo) } render() { if (this.state.hasError) { return (

Something went wrong

{this.state.error?.message}

) } return this.props.children } } // Usage ``` ## 애니메이션 패턴 ### Framer Motion 애니메이션 ```typescript import { motion, AnimatePresence } from 'framer-motion' // PASS: List animations export function AnimatedMarketList({ markets }: { markets: Market[] }) { return ( {markets.map(market => ( ))} ) } // PASS: Modal animations export function Modal({ isOpen, onClose, children }: ModalProps) { return ( {isOpen && ( <> {children} )} ) } ``` ## 접근성 패턴 ### 키보드 네비게이션 ```typescript export function Dropdown({ options, onSelect }: DropdownProps) { const [isOpen, setIsOpen] = useState(false) const [activeIndex, setActiveIndex] = useState(0) const handleKeyDown = (e: React.KeyboardEvent) => { switch (e.key) { case 'ArrowDown': e.preventDefault() setActiveIndex(i => Math.min(i + 1, options.length - 1)) break case 'ArrowUp': e.preventDefault() setActiveIndex(i => Math.max(i - 1, 0)) break case 'Enter': e.preventDefault() onSelect(options[activeIndex]) setIsOpen(false) break case 'Escape': setIsOpen(false) break } } return (
{/* Dropdown implementation */}
) } ``` ### 포커스 관리 ```typescript export function Modal({ isOpen, onClose, children }: ModalProps) { const modalRef = useRef(null) const previousFocusRef = useRef(null) useEffect(() => { if (isOpen) { // Save currently focused element previousFocusRef.current = document.activeElement as HTMLElement // Focus modal modalRef.current?.focus() } else { // Restore focus when closing previousFocusRef.current?.focus() } }, [isOpen]) return isOpen ? (
e.key === 'Escape' && onClose()} > {children}
) : null } ``` **기억하세요**: 모던 프론트엔드 패턴은 유지보수 가능하고 고성능인 사용자 인터페이스를 가능하게 합니다. 프로젝트 복잡도에 맞는 패턴을 선택하세요.