데이터 패칭(Data Fetching)과 캐싱 완벽 제어
Next.js 14에서는 복잡했던 상태 관리 라이브러리(Redux, React Query 등) 없이도, 네이티브 fetch() API의 확장을 통해 데이터 요청과 캐싱을 완벽하게 제어할 수 있습니다.
서버 컴포넌트에서의 데이터 패칭 장점
- 보안성 확보: 브라우저 네트워크 탭에 API 통신 내역이 노출되지 않아, 민감한 DB 접속 정보나 API Key를 안전하게 보호합니다.
- 워터폴(Waterfall) 방지: 여러 데이터를 동시에 가져와야 할 때
Promise.all을 사용하여 클라이언트 측에서 발생하는 병목 현상을 해결할 수 있습니다. - 자동 중복 제거: 같은 컴포넌트 트리 내에서 동일한
fetch요청이 여러 번 발생해도, Next.js가 자체적으로 1번만 요청하도록 중복 제거(Deduplication) 해줍니다.
// ==========================================
// 📂 app/news/page.tsx
// 서버 컴포넌트에서 fetch 캐싱 옵션 활용하기
// ==========================================
export default async function NewsPage() {
// 1. 실시간 데이터 (캐시 안함 - 매번 요청)
const realtimeRes = await fetch('https://api.example.com/stock-price', {
cache: 'no-store' // 캐시를 전혀 하지 않음 (SSR 방식)
});
const stock = await realtimeRes.json();
// 2. 주기적 갱신 데이터 (10초마다 캐시 갱신 - ISR 방식)
const newsRes = await fetch('https://api.example.com/latest-news', {
next: { revalidate: 10 } // 10초 동안은 빠르고 동일한 응답 반환
});
const newsList = await newsRes.json();
return (
<div className="p-8 space-y-8">
<section className="bg-red-50 p-6 rounded-xl border border-red-200">
<h2 className="text-xl font-bold text-red-600 mb-2">📈 실시간 삼성전자 주가</h2>
<p className="text-3xl font-mono">{stock.price.toLocaleString()} 원</p>
<p className="text-sm text-gray-500 mt-2">* 새로고침할 때마다 데이터가 변동됩니다.</p>
</section>
<section className="bg-blue-50 p-6 rounded-xl border border-blue-200">
<h2 className="text-xl font-bold text-blue-600 mb-4">📰 최근 뉴스 (10초 캐시)</h2>
<ul className="space-y-2">
{newsList.map((news: any) => (
<li key={news.id} className="text-gray-800 border-b pb-2">{news.title}</li>
))}
</ul>
<p className="text-sm text-gray-500 mt-4">* 10초 내에 새로고침하면 DB를 조회하지 않고 엄청 빠르게 캐시를 줍니다.</p>
</section>
</div>
);
}