โš›๏ธ

React & Next.js ์น˜ํŠธ์‹œํŠธ

React 19/18 ํ•ต์‹ฌ ํ›…, ์ปดํฌ๋„ŒํŠธ ํŒจํ„ด, Next.js 15/14 App Router ํŒŒ์ผ ๊ทœ์•ฝ, ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ(RSC), ์„œ๋ฒ„ ์•ก์…˜, ๋ฐ์ดํ„ฐ ํŽ˜์นญ/์บ์‹ฑ, Route Handlers ๋ฐ ๋ฏธ๋“ค์›จ์–ด ์™„๋ฒฝ ๊ฐ€์ด๋“œ

--views
๋‹จ์ˆ˜:
#react#nextjs#next.js#frontend#hooks#app-router#server-components#typescript#rsc#server-actions#ssr์ตœ์ข… ์—…๋ฐ์ดํŠธ: 2026-10-03

1. ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ & ์„ค์น˜ (Vite / Next.js)

๐Ÿ’ป ์‹œ์Šคํ…œ ์„ค์น˜ ๋ฐ ์‹คํ–‰ ์š”๊ตฌ์‚ฌ์–‘ (System Requirements)

ํ•ญ๋ชฉ์ตœ์†Œ ์‚ฌ์–‘ (Minimum)๊ถŒ์žฅ ์‚ฌ์–‘ (Recommended)์ฐธ๊ณ  ๋ฐ ๋น„๊ณ 
์šด์˜์ฒด์ œ (OS)Linux, macOS, Windows 10/11macOS (Apple Silicon), Ubuntu 22.04 LTS, Windows 11Node.js ๊ตฌ๋™ ๊ฐ€๋Šฅ ๋ชจ๋“  64-bit OS
CPU2 ์ฝ”์–ด ์ด์ƒ4 ์ฝ”์–ด ์ด์ƒNext.js SSR/SSG ํŽ˜์ด์ง€ ์‚ฌ์ „ ๋ Œ๋”๋ง ๋ฐ SWC/Turbopack ์ปดํŒŒ์ผ
๋ฉ”๋ชจ๋ฆฌ (RAM)2 GB ์ด์ƒ4 GB ~ 8 GB ์ด์ƒNext.js ๊ฐœ๋ฐœ ์„œ๋ฒ„ HMR ๋ฐ ํ”„๋กœ๋•์…˜ ๋นŒ๋“œ ๋ฉ”๋ชจ๋ฆฌ
๋””์Šคํฌ (Storage)2 GB ์ด์ƒ์˜ ์—ฌ์œ  ๊ณต๊ฐ„10 GB ์ด์ƒ์˜ SSDnode_modules, .next ๋นŒ๋“œ ์บ์‹œ
๋„คํŠธ์›Œํฌ / ๋Ÿฐํƒ€์ž„Node.js 18.18+ ๋˜๋Š” 20+ LTSnpm, pnpm ๋˜๋Š” yarn๋ชจ๋˜ ์›น ๋ธŒ๋ผ์šฐ์ € (Chrome, Firefox, Safari, Edge)

React ๋‹จ๋… SPA ํ”„๋กœ์ ํŠธ๋Š” Vite๋ฅผ, ํ’€์Šคํƒ SSR/SSG ์›น ์• ํ”Œ๋ฆฌ์ผ€์ด์…˜์€ Next.js App Router๋ฅผ ์‚ฌ์šฉํ•ฉ๋‹ˆ๋‹ค.

# โšก [1] Vite ๊ธฐ๋ฐ˜ React 19 + TypeScript ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ (ํด๋ผ์ด์–ธํŠธ SPA)
npm create vite@latest my-react-app -- --template react-ts
cd my-react-app
npm install
npm run dev

# ๐Ÿš€ [2] Next.js 15 / 14 ์ตœ์‹  ํ”„๋กœ์ ํŠธ ์ƒ์„ฑ (๊ณต์‹ App Router ๊ธฐ๋ณธ ์ ์šฉ)
npx create-next-app@latest my-next-app
# ๊ถŒ์žฅ ๋Œ€ํ™”ํ˜• ์„ค์ •:
# โœ” Would you like to use TypeScript? โ€ฆ Yes
# โœ” Would you like to use ESLint? โ€ฆ Yes
# โœ” Would you like to use Tailwind CSS? โ€ฆ Yes
# โœ” Would you like your code inside a `src/` directory? โ€ฆ Yes
# โœ” Would you like to use App Router? (recommended) โ€ฆ Yes
# โœ” Would you like to use Turbopack for `next dev`? โ€ฆ Yes
# โœ” Would you like to customize the import alias (@/*)? โ€ฆ No

# ๐Ÿ› ๏ธ [3] ์ž์ฃผ ์“ฐ๋Š” ํ•ต์‹ฌ ํŒจํ‚ค์ง€ ์›๋ผ์ด๋„ˆ ์„ค์น˜
# ์•„์ด์ฝ˜, ์œ ํ‹ธ๋ฆฌํ‹ฐ, ์ƒํƒœ๊ด€๋ฆฌ, ๊ฒ€์ฆ ๋ผ์ด๋ธŒ๋Ÿฌ๋ฆฌ
npm install lucide-react clsx tailwind-merge zustand zod

App Router ๊ธฐ๋ณธ ๋””๋ ‰ํ† ๋ฆฌ ๊ตฌ์กฐ (src/app)

src/
โ”œโ”€โ”€ app/
โ”‚   โ”œโ”€โ”€ layout.tsx         # ๋ฃจํŠธ ๋ ˆ์ด์•„์›ƒ (HTML <html>, <body> ํฌํ•จ, ํ•„์ˆ˜)
โ”‚   โ”œโ”€โ”€ page.tsx           # ๋ฉ”์ธ ํ™ˆ ํŽ˜์ด์ง€ (/)
โ”‚   โ”œโ”€โ”€ loading.tsx        # ๋กœ๋”ฉ UI (React Suspense ๊ธฐ๋ฐ˜ ์ž๋™ ๋ž˜ํ•‘)
โ”‚   โ”œโ”€โ”€ error.tsx          # ์—๋Ÿฌ ๋ฐ”์šด๋”๋ฆฌ ('use client' ํ•„์ˆ˜)
โ”‚   โ”œโ”€โ”€ not-found.tsx      # 404 ํŽ˜์ด์ง€
โ”‚   โ”œโ”€โ”€ api/
โ”‚   โ”‚   โ””โ”€โ”€ hello/route.ts # Route Handler (REST API ์—”๋“œํฌ์ธํŠธ)
โ”‚   โ””โ”€โ”€ blog/
โ”‚       โ”œโ”€โ”€ page.tsx       # /blog ํŽ˜์ด์ง€
โ”‚       โ””โ”€โ”€ [slug]/
โ”‚           โ””โ”€โ”€ page.tsx   # /blog/:slug ๋™์  ๋ผ์šฐํŠธ

2. React ํ•ต์‹ฌ ํ›… (Core Hooks)

ํ•จ์ˆ˜ํ˜• ์ปดํฌ๋„ŒํŠธ์—์„œ ์ƒํƒœ์™€ ๋ถ€์ˆ˜ ํšจ๊ณผ๋ฅผ ๋‹ค๋ฃจ๋Š” ๊ฐ€์žฅ ํ•„์ˆ˜์ ์ธ ํ›…๋“ค์ž…๋‹ˆ๋‹ค.

import React, { useState, useEffect, useRef, useMemo, useCallback } from 'react';

export default function CoreHooksDemo({ filterKeyword }: { filterKeyword: string }) {
  // ๐ŸŽฏ [1] useState: ์ƒํƒœ ์„ ์–ธ ๋ฐ ๋ถˆ๋ณ€์„ฑ ์—…๋ฐ์ดํŠธ
  const [count, setCount] = useState<number>(0);
  const [user, setUser] = useState({ name: 'Lucky', theme: 'dark' });

  // ํ•จ์ˆ˜ํ˜• ์—…๋ฐ์ดํŠธ (์ด์ „ ์ƒํƒœ ๋ณด์žฅ) & ๊ฐ์ฒด ์Šคํ”„๋ ˆ๋“œ ๋ถˆ๋ณ€์„ฑ ์œ ์ง€
  const increment = () => setCount((prev) => prev + 1);
  const updateTheme = (newTheme: string) => setUser((prev) => ({ ...prev, theme: newTheme }));

  // ๐Ÿ”Œ [2] useEffect: ์ƒ๋ช…์ฃผ๊ธฐ ๋ฐ ์‚ฌ์ด๋“œ ์ดํŽ™ํŠธ ๊ด€๋ฆฌ
  useEffect(() => {
    // ๋งˆ์šดํŠธ ์‹œ ๋˜๋Š” count ๋ณ€๊ฒฝ ์‹œ ์‹คํ–‰
    const timer = setInterval(() => console.log('Heartbeat'), 10000);

    // ํด๋ฆฐ์—… ํ•จ์ˆ˜ (์–ธ๋งˆ์šดํŠธ ์‹œ ๋˜๋Š” ๋‹ค์Œ effect ์‹คํ–‰ ์ง์ „ ๋ฆฌ์†Œ์Šค ํ•ด์ œ)
    return () => clearInterval(timer);
  }, [count]); // ์˜์กด์„ฑ ๋ฐฐ์—ด: []์ด๋ฉด ๋งˆ์šดํŠธ ์‹œ 1ํšŒ๋งŒ ์‹คํ–‰

  // ๐Ÿ“Œ [3] useRef: DOM ์—˜๋ฆฌ๋จผํŠธ ์ง์ ‘ ์ฐธ์กฐ ๋˜๋Š” ๋ Œ๋”๋ง์„ ์œ ๋ฐœํ•˜์ง€ ์•Š๋Š” ๊ฐ’ ์ €์žฅ
  const inputRef = useRef<HTMLInputElement>(null);
  const renderCountRef = useRef<number>(0);
  renderCountRef.current += 1;

  const handleFocus = () => inputRef.current?.focus();

  // ๐Ÿง  [4] useMemo: ๊ณ ๋น„์šฉ ์—ฐ์‚ฐ ๊ฒฐ๊ณผ๊ฐ’ ์บ์‹ฑ (๋ฉ”๋ชจ์ด์ œ์ด์…˜)
  const expensiveList = useMemo(() => {
    return Array.from({ length: 1000 }, (_, i) => `Item #${i}`).filter((item) =>
      item.includes(filterKeyword)
    );
  }, [filterKeyword]);

  // ๐Ÿ” [5] useCallback: ์ž์‹ ์ปดํฌ๋„ŒํŠธ์— ์ „๋‹ฌ๋˜๋Š” ์ฝœ๋ฐฑ ํ•จ์ˆ˜ ์žฌ์ƒ์„ฑ ๋ฐฉ์ง€
  const handleDelete = useCallback((id: number) => {
    console.log('Delete item:', id);
  }, []); // ์˜์กด์„ฑ์ด ์—†์œผ๋ฉด ์ตœ์ดˆ 1ํšŒ๋งŒ ํ•จ์ˆ˜ ์ƒ์„ฑ

  return (
    <div>
      <input ref={inputRef} placeholder="์ž…๋ ฅ..." />
      <button onClick={handleFocus}>ํฌ์ปค์Šค ์ด๋™</button>
      <button onClick={increment}>ํด๋ฆญ: {count}</button>
    </div>
  );
}

3. React 18 & 19 ๊ณ ๊ธ‰ ํ›… (Transitions, Id, Action)

๋™์‹œ์„ฑ(Concurrency)๊ณผ ๋ชจ๋˜ ํผ ์ฒ˜๋ฆฌ๋ฅผ ์œ„ํ•œ ๊ณ ๊ธ‰ ํ›…์ž…๋‹ˆ๋‹ค.

'use client';
import { useTransition, useId, useOptimistic, useActionState } from 'react';

// โšก [1] useTransition: UI ๋ Œ๋”๋ง ๋ธ”๋กœํ‚น ๋ฐฉ์ง€ (์šฐ์„ ์ˆœ์œ„๊ฐ€ ๋‚ฎ์€ ์—…๋ฐ์ดํŠธ)
export function SearchBox({ onSearch }: { onSearch: (q: string) => void }) {
  const [isPending, startTransition] = useTransition();

  const handleChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    // ํƒ€์ดํ•‘ ์ธํ’‹์€ ์ฆ‰์‹œ ๋ฐ˜์‘ํ•˜๊ณ , ๋ฌด๊ฑฐ์šด ๊ฒ€์ƒ‰ ๋ Œ๋”๋ง์€ ํŠธ๋žœ์ง€์…˜์œผ๋กœ ์ง€์—ฐ ์ฒ˜๋ฆฌ
    startTransition(() => {
      onSearch(e.target.value);
    });
  };

  return (
    <div>
      <input onChange={handleChange} placeholder="๊ฒ€์ƒ‰์–ด ์ž…๋ ฅ..." />
      {isPending && <span className="spinner">๊ฒ€์ƒ‰ ๊ฒฐ๊ณผ ๋กœ๋”ฉ ์ค‘...</span>}
    </div>
  );
}

// ๐Ÿ†” [2] useId: SSR๊ณผ ํด๋ผ์ด์–ธํŠธ ๊ฐ„ ํ•˜์ด๋“œ๋ ˆ์ด์…˜ ๋ถˆ์ผ์น˜ ์—†๋Š” ๊ณ ์œ  ID ์ƒ์„ฑ
export function AccessibleInput({ label }: { label: string }) {
  const id = useId();
  return (
    <div>
      <label htmlFor={id}>{label}</label>
      <input id={id} type="text" />
    </div>
  );
}

// ๐Ÿš€ [3] useOptimistic (React 19): ์„œ๋ฒ„ ์‘๋‹ต ์ „ UI๋ฅผ ๋จผ์ € ๊ฐฑ์‹ ํ•˜๋Š” ๋‚™๊ด€์  ์—…๋ฐ์ดํŠธ
export function MessageList({ messages, sendMessageAction }: any) {
  const [optimisticMessages, setOptimistic] = useOptimistic(
    messages,
    (state: string[], newMsg: string) => [...state, `${newMsg} (์ „์†ก ์ค‘...)`]
  );

  const formAction = async (formData: FormData) => {
    const text = formData.get('message') as string;
    setOptimistic(text); // UI ์ฆ‰์‹œ ๋ฐ˜์˜
    await sendMessageAction(text); // ์‹ค์ œ ์„œ๋ฒ„ ์ „์†ก
  };

  return (
    <form action={formAction}>
      <ul>{optimisticMessages.map((m: string, i: number) => <li key={i}>{m}</li>)}</ul>
      <input name="message" required />
      <button type="submit">์ „์†ก</button>
    </form>
  );
}

4. ์ปดํฌ๋„ŒํŠธ ํŒจํ„ด & ์ปค์Šคํ…€ ํ›… (Custom Hooks)

์žฌ์‚ฌ์šฉ ๊ฐ€๋Šฅํ•œ UI ์ปดํฌ๋„ŒํŠธ ์„ค๊ณ„์™€ ๋น„์ฆˆ๋‹ˆ์Šค ๋กœ์ง ๋ถ„๋ฆฌ ํŒจํ„ด์ž…๋‹ˆ๋‹ค.

import React, { useState, useEffect } from 'react';

// ๐Ÿ“ฆ [1] ํƒ€์ž… ์•ˆ์ „ํ•œ Props ์ธํ„ฐํŽ˜์ด์Šค ์ •์˜ (React.FC ์ง€์–‘, Props ์ง์ ‘ ํƒ€์ดํ•‘)
interface CardProps {
  title: string;
  badge?: string;
  children: React.ReactNode; // ์Šฌ๋กฏ ํ˜•ํƒœ์˜ ์ž์‹ ๋…ธ๋“œ
  variant?: 'primary' | 'secondary';
  onAction?: () => void;
}

export function Card({ title, badge, children, variant = 'primary', onAction }: CardProps) {
  return (
    <div className={`card card-${variant}`}>
      <header className="flex justify-between items-center">
        <h3>{title}</h3>
        {badge && <span className="badge">{badge}</span>}
      </header>
      <div className="card-body">{children}</div>
      {onAction && <button onClick={onAction}>ํ™•์ธ</button>}
    </div>
  );
}

// ๐Ÿ› ๏ธ [2] ์‹ค์ „ ์ปค์Šคํ…€ ํ›…: useDebounce (๊ฒ€์ƒ‰์ฐฝ API ์š”์ฒญ ์ตœ์ ํ™”)
export function useDebounce<T>(value: T, delay: number = 300): T {
  const [debouncedValue, setDebouncedValue] = useState<T>(value);

  useEffect(() => {
    const handler = setTimeout(() => setDebouncedValue(value), delay);
    return () => clearTimeout(handler);
  }, [value, delay]);

  return debouncedValue;
}

// ๐Ÿ’พ [3] ์‹ค์ „ ์ปค์Šคํ…€ ํ›…: useLocalStorage
export function useLocalStorage<T>(key: string, initialValue: T) {
  const [storedValue, setStoredValue] = useState<T>(() => {
    if (typeof window === 'undefined') return initialValue;
    try {
      const item = window.localStorage.getItem(key);
      return item ? JSON.parse(item) : initialValue;
    } catch {
      return initialValue;
    }
  });

  const setValue = (value: T | ((val: T) => T)) => {
    try {
      const valueToStore = value instanceof Function ? value(storedValue) : value;
      setStoredValue(valueToStore);
      if (typeof window !== 'undefined') {
        window.localStorage.setItem(key, JSON.stringify(valueToStore));
      }
    } catch (err) {
      console.error(err);
    }
  };

  return [storedValue, setValue] as const;
}

5. Next.js App Router ๋ผ์šฐํŒ… & ํŒŒ์ผ ๊ทœ์•ฝ

ํด๋” ๊ตฌ์กฐ๊ฐ€ ๊ณง ์›น URL ๊ฒฝ๋กœ๊ฐ€ ๋˜๋ฉฐ, ํŠน์ˆ˜ ํŒŒ์ผ๋“ค์„ ํ†ตํ•ด ๋ ˆ์ด์•„์›ƒ๊ณผ ์ƒํƒœ๋ฅผ ์บก์Аํ™”ํ•ฉ๋‹ˆ๋‹ค.

// ๐Ÿ“„ app/blog/[slug]/page.tsx (๋™์  ๋ผ์šฐํŠธ ํŽ˜์ด์ง€)
// Next.js 15๋ถ€ํ„ฐ params๋Š” Promise์ž…๋‹ˆ๋‹ค (๋น„๋™๊ธฐ await ์ฒ˜๋ฆฌ ํ•„์ˆ˜)
interface PageProps {
  params: Promise<{ slug: string }>;
  searchParams: Promise<{ [key: string]: string | string[] | undefined }>;
}

export default async function BlogPostPage({ params, searchParams }: PageProps) {
  const { slug } = await params;
  const query = await searchParams;

  return (
    <article>
      <h1>ํฌ์ŠคํŠธ: {slug}</h1>
      <p>๊ฒ€์ƒ‰ ํ•„ํ„ฐ: {query.tab || '๊ธฐ๋ณธ๊ฐ’'}</p>
    </article>
  );
}

// โš ๏ธ app/error.tsx (์—๋Ÿฌ ์ฒ˜๋ฆฌ ๋ฐ”์šด๋”๋ฆฌ - ๋ฐ˜๋“œ์‹œ Client Component์—ฌ์•ผ ํ•จ)
'use client';
export function ErrorBoundary({ error, reset }: { error: Error; reset: () => void }) {
  return (
    <div className="error-box">
      <h2>์˜ค๋ฅ˜๊ฐ€ ๋ฐœ์ƒํ–ˆ์Šต๋‹ˆ๋‹ค!</h2>
      <p>{error.message}</p>
      <button onClick={() => reset()}>๋‹ค์‹œ ์‹œ๋„</button>
    </div>
  );
}

// โณ app/loading.tsx (ํŽ˜์ด์ง€ ์ „ํ™˜ ์‹œ ์ž๋™ ๋ Œ๋”๋ง๋˜๋Š” ์Šค์ผˆ๋ ˆํ†ค UI)
export function LoadingSkeleton() {
  return <div className="animate-pulse bg-gray-200 h-64 rounded-xl" />;
}

// ๐Ÿšซ app/not-found.tsx (notFound() ํ•จ์ˆ˜ ํ˜ธ์ถœ ์‹œ ๋…ธ์ถœ)
import Link from 'next/link';
export default function NotFound() {
  return (
    <div>
      <h2>ํŽ˜์ด์ง€๋ฅผ ์ฐพ์„ ์ˆ˜ ์—†์Šต๋‹ˆ๋‹ค (404)</h2>
      <Link href="/">ํ™ˆ์œผ๋กœ ์ด๋™</Link>
    </div>
  );
}

6. ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ(RSC) vs ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ

Next.js App Router์˜ ๋ชจ๋“  ์ปดํฌ๋„ŒํŠธ๋Š” ๊ธฐ๋ณธ์ ์œผ๋กœ **React Server Component(RSC)**์ž…๋‹ˆ๋‹ค.

// ๐ŸŒ [1] ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ (Server Component, ๊ธฐ๋ณธ๊ฐ’)
// - ํด๋ผ์ด์–ธํŠธ JS ๋ฒˆ๋“ค์— ํฌํ•จ๋˜์ง€ ์•Š์Œ (0 KB)
// - ๋ฐ์ดํ„ฐ๋ฒ ์ด์Šค(Prisma, Supabase, SQL) ๋ฐ ์„œ๋ฒ„ ๋น„๋ฐ€ํ‚ค(API_KEY)์— ์ง์ ‘ ์ ‘๊ทผ ๊ฐ€๋Šฅ
// - useState, useEffect, onClick ๋“ฑ ๋ธŒ๋ผ์šฐ์ € ์ด๋ฒคํŠธ ์‚ฌ์šฉ ๋ถˆ๊ฐ€
import { db } from '@/lib/db';

export default async function UserProfile({ userId }: { userId: string }) {
  // DB ์ง์ ‘ ์กฐํšŒ (API ์—”๋“œํฌ์ธํŠธ ๊ฑฐ์น  ํ•„์š” ์—†์Œ)
  const user = await db.user.findUnique({ where: { id: userId } });

  return (
    <div>
      <h2>{user?.name}</h2>
      {/* ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ๋ฅผ ์ž์‹์œผ๋กœ ์ž„ํฌํŠธํ•˜์—ฌ ์‚ฌ์šฉ */}
      <FollowButton targetId={userId} />
    </div>
  );
}

// ๐Ÿ’ป [2] ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ (Client Component)
// - ํŒŒ์ผ ์ตœ์ƒ๋‹จ์— 'use client' ๋ช…์‹œ
// - onClick, onChange ๋“ฑ ์ด๋ฒคํŠธ ๋ฆฌ์Šค๋„ˆ์™€ useState, useEffect ์‚ฌ์šฉ ์‹œ ํ•„์ˆ˜
'use client';

import { useState } from 'react';

export function FollowButton({ targetId }: { targetId: string }) {
  const [isFollowing, setIsFollowing] = useState(false);

  return (
    <button onClick={() => setIsFollowing(!isFollowing)}>
      {isFollowing ? 'ํŒ”๋กœ์ž‰' : 'ํŒ”๋กœ์šฐ'}
    </button>
  );
}

// ๐Ÿ’ก [ํ•ต์‹ฌ ํŒจํ„ด] Server Component๋ฅผ Client Component์˜ children์œผ๋กœ ์ „๋‹ฌํ•˜๊ธฐ
// 'use client' ์ปดํฌ๋„ŒํŠธ ์•ˆ์—์„œ ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ๋ฅผ importํ•˜๋ฉด ํด๋ผ์ด์–ธํŠธ๋กœ ๋ณ€ํ™˜๋˜๋ฏ€๋กœ,
// ์•„๋ž˜์ฒ˜๋Ÿผ children ํ”„๋กญ์œผ๋กœ ์ „๋‹ฌํ•ด์•ผ ์„œ๋ฒ„ ๋ Œ๋”๋ง ์ด์ ์„ ์œ ์ง€ํ•  ์ˆ˜ ์žˆ์Šต๋‹ˆ๋‹ค.
// <ClientModal><ServerHeavyContent /></ClientModal>

7. ๋ฐ์ดํ„ฐ ํŽ˜์นญ, ์บ์‹ฑ & Revalidation

์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ์—์„œ๋Š” fetch ํ•จ์ˆ˜๊ฐ€ ๋ธŒ๋ผ์šฐ์ €๊ฐ€ ์•„๋‹Œ ์„œ๋ฒ„ ํ™˜๊ฒฝ์—์„œ ํ™•์žฅ๋œ ์บ์‹œ ์˜ต์…˜๊ณผ ํ•จ๊ป˜ ๋™์ž‘ํ•ฉ๋‹ˆ๋‹ค.

// ๐Ÿ“ฅ [1] ์ •์  ์บ์‹ฑ (๊ธฐ๋ณธ SSG ํšจ๊ณผ, ๋นŒ๋“œ ์‹œ์  ๋˜๋Š” ์ฒซ ์š”์ฒญ ์‹œ ์บ์‹œ ์œ ์ง€)
async function getStaticData() {
  const res = await fetch('https://api.example.com/data', {
    cache: 'force-cache', // ๊ธฐ๋ณธ๊ฐ’
  });
  return res.json();
}

// ๐Ÿ”„ [2] ๋™์  ํŽ˜์นญ (SSR ํšจ๊ณผ, ์š”์ฒญ๋งˆ๋‹ค ์ƒˆ๋กœ ๊ฐ€์ ธ์˜ค๊ธฐ)
async function getDynamicData() {
  const res = await fetch('https://api.example.com/stock-price', {
    cache: 'no-store', // ์บ์‹œํ•˜์ง€ ์•Š์Œ
  });
  return res.json();
}

// โฑ๏ธ [3] ์‹œ๊ฐ„ ๊ธฐ๋ฐ˜ ์žฌ๊ฒ€์ฆ (ISR - Incremental Static Regeneration)
async function getRevalidatedData() {
  const res = await fetch('https://api.example.com/posts', {
    next: { revalidate: 60 }, // 60์ดˆ๋งˆ๋‹ค ๋ฐฑ๊ทธ๋ผ์šด๋“œ ์žฌ๊ฒ€์ฆ
  });
  return res.json();
}

// ๐Ÿท๏ธ [4] ํƒœ๊ทธ ๊ธฐ๋ฐ˜ ์˜จ๋””๋งจ๋“œ ์žฌ๊ฒ€์ฆ (On-Demand Revalidation)
async function getTaggedData() {
  const res = await fetch('https://api.example.com/products', {
    next: { tags: ['products'] }, // ํƒœ๊ทธ ์ง€์ •
  });
  return res.json();
}

// โšก [5] ์˜จ๋””๋งจ๋“œ ์žฌ๊ฒ€์ฆ ํŠธ๋ฆฌ๊ฑฐ (Server Action ๋˜๋Š” Route Handler์—์„œ ํ˜ธ์ถœ)
import { revalidateTag, revalidatePath } from 'next/cache';

export async function clearCacheAction() {
  'use server';
  revalidateTag('products');       // 'products' ํƒœ๊ทธ๊ฐ€ ๋‹ฌ๋ฆฐ ๋ชจ๋“  ์บ์‹œ ์ฆ‰์‹œ ๋ฌดํšจํ™”
  revalidatePath('/blog/[slug]'); // ํŠน์ • ๊ฒฝ๋กœ ์ฆ‰์‹œ ์žฌ๊ฒ€์ฆ
}

// ๐Ÿ“‘ [6] ์ •์  ๋™์  ๊ฒฝ๋กœ ์‚ฌ์ „ ์ƒ์„ฑ (generateStaticParams)
export async function generateStaticParams() {
  const posts = await fetch('https://api.example.com/posts').then((res) => res.json());
  return posts.map((post: any) => ({ slug: post.id.toString() }));
}

8. ์„œ๋ฒ„ ์•ก์…˜ (Server Actions: โ€˜use serverโ€™)

๋ณ„๋„์˜ REST API ๋ผ์šฐํŠธ ์—†์ด, ํด๋ผ์ด์–ธํŠธ ํผ์ด๋‚˜ ๋ฒ„ํŠผ์—์„œ ์„œ๋ฒ„ ํ•จ์ˆ˜๋ฅผ ์ง์ ‘ ํ˜ธ์ถœํ•˜์—ฌ DB ์ˆ˜์ • ๋ฐ ๋ณ€ํ˜•(Mutation)์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

// ๐Ÿ“ app/actions/user.ts (๋ณ„๋„ ํŒŒ์ผ๋กœ ๋ถ„๋ฆฌ ์‹œ ํŒŒ์ผ ์ƒ๋‹จ์— 'use server')
'use server';

import { revalidatePath } from 'next/cache';
import { z } from 'zod';

const schema = z.object({
  email: z.string().email('์˜ฌ๋ฐ”๋ฅธ ์ด๋ฉ”์ผ ํ˜•์‹์ด ์•„๋‹™๋‹ˆ๋‹ค.'),
  username: z.string().min(2, '์ด๋ฆ„์€ ์ตœ์†Œ 2๊ธ€์ž ์ด์ƒ์ด์–ด์•ผ ํ•ฉ๋‹ˆ๋‹ค.'),
});

export async function createUserAction(prevState: any, formData: FormData) {
  const rawData = {
    email: formData.get('email'),
    username: formData.get('username'),
  };

  // 1. ์œ ํšจ์„ฑ ๊ฒ€์ฆ
  const validated = schema.safeParse(rawData);
  if (!validated.success) {
    return { success: false, errors: validated.error.flatten().fieldErrors };
  }

  // 2. DB ์ž‘์—… (์˜ˆ: Prisma / Supabase ํ˜ธ์ถœ)
  // await db.user.create({ data: validated.data });

  // 3. ์บ์‹œ ๊ฐฑ์‹ 
  revalidatePath('/users');
  return { success: true, message: '์„ฑ๊ณต์ ์œผ๋กœ ๋“ฑ๋ก๋˜์—ˆ์Šต๋‹ˆ๋‹ค.' };
}

// ๐Ÿ“„ app/users/new/page.tsx (ํด๋ผ์ด์–ธํŠธ ํผ ์ปดํฌ๋„ŒํŠธ)
'use client';
import { useActionState } from 'react';
import { useFormStatus } from 'react-dom';
import { createUserAction } from '@/app/actions/user';

function SubmitButton() {
  const { pending } = useFormStatus(); // ๋ถ€๋ชจ <form>์˜ ์ œ์ถœ ์ง„ํ–‰ ์ƒํƒœ ๊ฐ์ง€
  return (
    <button type="submit" disabled={pending} className="btn-primary">
      {pending ? '์ €์žฅ ์ค‘...' : '์‚ฌ์šฉ์ž ๋“ฑ๋ก'}
    </button>
  );
}

export default function NewUserForm() {
  const [state, formAction] = useActionState(createUserAction, null);

  return (
    <form action={formAction} className="space-y-4">
      <div>
        <input name="username" placeholder="์ด๋ฆ„" required />
        {state?.errors?.username && <p className="text-red-500">{state.errors.username[0]}</p>}
      </div>
      <div>
        <input name="email" type="email" placeholder="์ด๋ฉ”์ผ" required />
        {state?.errors?.email && <p className="text-red-500">{state.errors.email[0]}</p>}
      </div>
      <SubmitButton />
      {state?.success && <p className="text-green-500">{state.message}</p>}
    </form>
  );
}

9. Next.js ๋‚ด์žฅ ์ตœ์ ํ™” ์ปดํฌ๋„ŒํŠธ & ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ

์›น ์„ฑ๋Šฅ(Core Web Vitals)๊ณผ ๊ฒ€์ƒ‰ ์—”์ง„ ์ตœ์ ํ™”(SEO)๋ฅผ ์œ„ํ•œ ๋‚ด์žฅ ๊ธฐ๋Šฅ์ž…๋‹ˆ๋‹ค.

// ๐Ÿ–ผ๏ธ [1] next/image: ์ž๋™ WebP ๋ณ€ํ™˜, Lazy Loading, ๋ ˆ์ด์•„์›ƒ ์‹œํ”„ํŠธ ๋ฐฉ์ง€
import Image from 'next/image';
import Link from 'next/link';

export function Banner() {
  return (
    <div>
      {/* LCP ์ฃผ์š” ์ด๋ฏธ์ง€์ผ ๊ฒฝ์šฐ priority={true} ์ ์šฉ */}
      <Image
        src="/hero-banner.png"
        alt="๋ฉ”์ธ ๋ฐฐ๋„ˆ"
        width={1200}
        height={600}
        priority
        className="rounded-lg object-cover"
      />
      {/* ๐Ÿ”— [2] next/link: ๋ทฐํฌํŠธ์— ๋“ค์–ด์˜ค๋ฉด ๋ฐฑ๊ทธ๋ผ์šด๋“œ ํ”„๋ฆฌํŽ˜์น˜(prefetch) ์ž๋™ ์ˆ˜ํ–‰ */}
      <Link href="/dashboard" prefetch={true} className="text-blue-500 hover:underline">
        ๋Œ€์‹œ๋ณด๋“œ๋กœ ์ด๋™
      </Link>
    </div>
  );
}

// ๐Ÿ” [3] ์ •์  ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ (SEO)
export const metadata = {
  title: 'Next.js ๋งˆ์Šคํ„ฐ ๊ฐ€์ด๋“œ | LuckyTechWorld',
  description: 'App Router๋ถ€ํ„ฐ ์„œ๋ฒ„ ์•ก์…˜๊นŒ์ง€ ๋‹ค๋ฃจ๋Š” ์ข…ํ•ฉ ๋ ˆํผ๋Ÿฐ์Šค',
  openGraph: {
    title: 'Next.js ๋งˆ์Šคํ„ฐ ๊ฐ€์ด๋“œ',
    images: ['/og-image.png'],
  },
};

// ๐ŸŽฏ [4] ๋™์  ๋ฉ”ํƒ€๋ฐ์ดํ„ฐ (ํฌ์ŠคํŠธ ์ œ๋ชฉ/์ƒ์„ธ ์กฐํšŒ ๊ธฐ๋ฐ˜ ๋™์  ์ƒ์„ฑ)
export async function generateMetadata({ params }: { params: Promise<{ id: string }> }) {
  const { id } = await params;
  const post = await fetch(`https://api.example.com/posts/${id}`).then((r) => r.json());
  return {
    title: `${post.title} - ๊ธฐ์ˆ  ๋ธ”๋กœ๊ทธ`,
    description: post.summary,
  };
}

// ๐Ÿ”ค [5] next/font: ๊ตฌ๊ธ€ ํฐํŠธ ๋นŒ๋“œ ํƒ€์ž„ ์ž์ฒด ํ˜ธ์ŠคํŒ… (์™ธ๋ถ€ ์š”์ฒญ ์ œ๋กœ)
import { Inter } from 'next/font/google';
const inter = Inter({ subsets: ['latin'], display: 'swap' });
export function RootLayout({ children }: { children: React.ReactNode }) {
  return (
    <html lang="ko" className={inter.className}>
      <body>{children}</body>
    </html>
  );
}

10. Route Handlers (app/api/โ€ฆ/route.ts)

ํด๋ผ์ด์–ธํŠธ๋‚˜ ์™ธ๋ถ€ ์‹œ์Šคํ…œ์—์„œ ํ˜ธ์ถœํ•  ์ˆ˜ ์žˆ๋Š” ์›น ํ‘œ์ค€ ๊ธฐ๋ฐ˜์˜ REST API ์—”๋“œํฌ์ธํŠธ์ž…๋‹ˆ๋‹ค.

// ๐Ÿ“ app/api/items/route.ts
import { NextRequest, NextResponse } from 'next/server';

// ๐ŸŸข GET: ๋ชฉ๋ก ์กฐํšŒ ๋ฐ ์ฟผ๋ฆฌ ํŒŒ๋ผ๋ฏธํ„ฐ ํŒŒ์‹ฑ
export async function GET(request: NextRequest) {
  const searchParams = request.nextUrl.searchParams;
  const page = searchParams.get('page') || '1';
  const keyword = searchParams.get('q') || '';

  const items = [{ id: 1, name: 'Item A' }, { id: 2, name: 'Item B' }];

  return NextResponse.json({
    success: true,
    page: Number(page),
    keyword,
    data: items,
  }, { status: 200 });
}

// ๐Ÿ”ต POST: JSON Body ๋ฐ์ดํ„ฐ ์ˆ˜์‹  ๋ฐ ์‘๋‹ต
export async function POST(request: NextRequest) {
  try {
    const body = await request.json();

    if (!body.title) {
      return NextResponse.json({ error: '์ œ๋ชฉ์€ ํ•„์ˆ˜ ํ•ญ๋ชฉ์ž…๋‹ˆ๋‹ค.' }, { status: 400 });
    }

    // ์‹ ๊ทœ ๋ฐ์ดํ„ฐ DB ์‚ฝ์ž… ์˜ˆ์‹œ...
    const newItem = { id: Date.now(), title: body.title };

    return NextResponse.json(newItem, { status: 201 });
  } catch (err) {
    return NextResponse.json({ error: '์ž˜๋ชป๋œ JSON ๋ฐ”๋”” ์š”์ฒญ์ž…๋‹ˆ๋‹ค.' }, { status: 500 });
  }
}

// ๐Ÿ“ app/api/items/[id]/route.ts (๋™์  ๋งค๊ฐœ๋ณ€์ˆ˜ ์ฒ˜๋ฆฌ)
export async function DELETE(
  request: NextRequest,
  { params }: { params: Promise<{ id: string }> }
) {
  const { id } = await params;
  return NextResponse.json({ message: `ID ${id} ์‚ญ์ œ ์™„๋ฃŒ` });
}

11. ๋ฏธ๋“ค์›จ์–ด(Middleware) & ์ธ์ฆ/๋ณด์•ˆ ์ฒ˜๋ฆฌ

์š”์ฒญ์ด ์™„๋ฃŒ๋˜๊ธฐ ์ „์— ์‹คํ–‰๋˜์–ด ์ธ์ฆ ์ฒดํฌ, ๋ฆฌ๋””๋ ‰์…˜, ํ—ค๋” ์žฌ์ž‘์„ฑ์„ ์ˆ˜ํ–‰ํ•ฉ๋‹ˆ๋‹ค.

// ๐Ÿ“„ middleware.ts (src/ ๋ฐ”๋กœ ์•„๋ž˜ ๋˜๋Š” ํ”„๋กœ์ ํŠธ ๋ฃจํŠธ์— ์œ„์น˜)
import { NextResponse } from 'next/server';
import type { NextRequest } from 'next/server';

export function middleware(request: NextRequest) {
  const token = request.cookies.get('session_token')?.value;
  const pathname = request.nextUrl.pathname;

  // ๐Ÿ”’ [1] ๋ณดํ˜ธ๋œ ๊ด€๋ฆฌ์ž/๋Œ€์‹œ๋ณด๋“œ ๊ฒฝ๋กœ ์ธ์ฆ ๊ฒ€์‚ฌ
  if (pathname.startsWith('/dashboard') || pathname.startsWith('/admin')) {
    if (!token) {
      // ๋ฏธ์ธ์ฆ ์‹œ ๋กœ๊ทธ์ธ ํŽ˜์ด์ง€๋กœ ๋ฆฌ๋””๋ ‰์…˜ (์›๋ž˜ ๊ฐ€๋ ค๋˜ URL์„ ์ฟผ๋ฆฌ์— ๋ณด์กด)
      const loginUrl = new URL('/login', request.url);
      loginUrl.searchParams.set('callbackUrl', pathname);
      return NextResponse.redirect(loginUrl);
    }
  }

  // ๐Ÿ›ก๏ธ [2] ๋ณด์•ˆ ํ—ค๋” ๋ฐ ์ปค์Šคํ…€ ์š”์ฒญ ํ—ค๋” ์ฃผ์ž… (Rewrite)
  const requestHeaders = new Headers(request.headers);
  requestHeaders.set('x-lucky-timestamp', Date.now().toString());

  const response = NextResponse.next({
    request: {
      headers: requestHeaders,
    },
  });

  // ์‘๋‹ต ๋ณด์•ˆ ํ—ค๋” ์ถ”๊ฐ€
  response.headers.set('X-Frame-Options', 'DENY');
  response.headers.set('X-Content-Type-Options', 'nosniff');

  return response;
}

// โš™๏ธ [3] ๋ฏธ๋“ค์›จ์–ด๊ฐ€ ์‹คํ–‰๋  ๊ฒฝ๋กœ ํ•„ํ„ฐ๋ง (์ •์  ํŒŒ์ผ ๋ฐ ํŒŒ๋น„์ฝ˜ ์ œ์™ธ ํ•„์ˆ˜)
export const config = {
  matcher: [
    /*
     * ๋‹ค์Œ์œผ๋กœ ์‹œ์ž‘ํ•˜๋Š” ๊ฒฝ๋กœ๋ฅผ ์ œ์™ธํ•œ ๋ชจ๋“  ์š”์ฒญ ๊ฒฝ๋กœ์— ๋ฏธ๋“ค์›จ์–ด ์ ์šฉ:
     * - api (API ๋ผ์šฐํŠธ ์ œ์™ธ ์‹œ)
     * - _next/static (์ •์  ํŒŒ์ผ)
     * - _next/image (์ด๋ฏธ์ง€ ์ตœ์ ํ™” ํŒŒ์ผ)
     * - favicon.ico (ํŒŒ๋น„์ฝ˜ ํŒŒ์ผ)
     */
    '/((?!_next/static|_next/image|favicon.ico).*)',
  ],
};

12. ์ƒํƒœ ๊ด€๋ฆฌ (Zustand) & ํ™˜๊ฒฝ๋ณ€์ˆ˜ ์„ค์ •

๊ฐ€์žฅ ๊ฐ€๋ณ๊ณ  ๋„๋ฆฌ ์“ฐ์ด๋Š” Zustand ์ „์—ญ ์ƒํƒœ ๊ด€๋ฆฌ์™€ ํ™˜๊ฒฝ๋ณ€์ˆ˜ ๊ทœ์น™์ž…๋‹ˆ๋‹ค.

// ๐Ÿป [1] Zustand ์ „์—ญ ์Šคํ† ์–ด ์ •์˜ (src/stores/useAuthStore.ts)
import { create } from 'zustand';
import { persist } from 'zustand/middleware';

interface User {
  id: string;
  name: string;
  email: string;
}

interface AuthState {
  user: User | null;
  isAuthenticated: boolean;
  login: (userData: User) => void;
  logout: () => void;
}

export const useAuthStore = create<AuthState>()(
  persist(
    (set) => ({
      user: null,
      isAuthenticated: false,
      login: (userData) => set({ user: userData, isAuthenticated: true }),
      logout: () => set({ user: null, isAuthenticated: false }),
    }),
    { name: 'auth-storage' } // ๋กœ์ปฌ ์Šคํ† ๋ฆฌ์ง€์— ์ž๋™ ์ €์žฅ
  )
);

// ๐Ÿ“„ [2] ์ปดํฌ๋„ŒํŠธ์—์„œ Zustand ์Šคํ† ์–ด ์‚ฌ์šฉ ์˜ˆ์‹œ
'use client';
export function UserStatus() {
  const { user, isAuthenticated, logout } = useAuthStore();
  if (!isAuthenticated) return <p>๋กœ๊ทธ์ธ์ด ํ•„์š”ํ•ฉ๋‹ˆ๋‹ค.</p>;
  return (
    <div>
      <p>ํ™˜์˜ํ•ฉ๋‹ˆ๋‹ค, {user?.name}๋‹˜!</p>
      <button onClick={logout}>๋กœ๊ทธ์•„์›ƒ</button>
    </div>
  );
}

๐ŸŒ ํ™˜๊ฒฝ๋ณ€์ˆ˜(.env) ๋ณด์•ˆ ๊ทœ์น™

# ๐Ÿ”’ [์„œ๋ฒ„ ์ „์šฉ ํ™˜๊ฒฝ๋ณ€์ˆ˜]
# ๋ธŒ๋ผ์šฐ์ € JS ๋ฒˆ๋“ค์— ์ ˆ๋Œ€ ํฌํ•จ๋˜์ง€ ์•Š์œผ๋ฉฐ, ์„œ๋ฒ„ ์ปดํฌ๋„ŒํŠธ/์„œ๋ฒ„ ์•ก์…˜/Route Handler์—์„œ๋งŒ ์ ‘๊ทผ ๊ฐ€๋Šฅ
DATABASE_URL="postgresql://user:password@localhost:5432/mydb"
JWT_SECRET_KEY="super-secret-key-only-server-knows"
OPENAI_API_KEY="sk-..."

# ๐ŸŒ [ํด๋ผ์ด์–ธํŠธ ๊ณต๊ฐœ ํ™˜๊ฒฝ๋ณ€์ˆ˜]
# 'NEXT_PUBLIC_' ์ ‘๋‘์‚ฌ๋ฅผ ๋ถ™์—ฌ์•ผ ๋ธŒ๋ผ์šฐ์ € ํด๋ผ์ด์–ธํŠธ ์ปดํฌ๋„ŒํŠธ('use client')์—์„œ ์ฝ์„ ์ˆ˜ ์žˆ์Œ
NEXT_PUBLIC_API_URL="https://api.example.com"
NEXT_PUBLIC_GA_TRACKING_ID="G-XXXXXXXXXX"
๐Ÿ’ฌ

์˜๊ฒฌ ๋ฐ ์งˆ๋ฌธ

0
0 / 1500