데이터 읽기
데이터를 읽는 위치에 따라 예측 가능한 코드를 작성할 수 있습니다. 상황에 맞는 최적의 방법을 선택하세요.
빠른 선택 가이드
- 서버(RSC): 서버 컴포넌트에서 초기 페이지 콘텐츠를 로딩할 때
nexus(def)
를 호출합니다. - 클라이언트: 클라이언트 컴포넌트에서 상호작용에 따른 데이터를 요청할 때
useNexusQuery(def)
를 사용합니다.
핵심 가이드: 초기 페이지 로드나 SEO에 중요한 데이터는 서버에서, 사용자 상호작용에 따라 변하거나 개인화된 데이터는 클라이언트에서 읽는 것이 좋습니다.
서버에서 데이터 읽기 (RSC)
import { nexus } from "next-nexus/server";
import { usersDefinition } from "@/definitions";
// Next.js 15+ (params가 Promise)
export default async function Page({
params,
}: {
params: Promise<{ id: string }>;
}) {
const { id } = await params;
const res = await nexus(usersDefinition.getById(id));
return <p>{res.data.id}</p>;
}
참고: Next.js 버전에 따라
Page
컴포넌트의props
를 다르게 사용해야 합니다.
- Next.js 15+:
params
와searchParams
가Promise
이므로,async/await
와 함께 사용해야 합니다.- Next.js 14.x 및 이전 버전: 동기 객체이므로
params.id
와 같이 바로 접근할 수 있습니다.
클라이언트에서 데이터 읽기 (Hook)
"use client";
import { useNexusQuery } from "next-nexus/client";
import { usersDefinition } from "@/definitions";
export function UserPanel({ id }: { id: string }) {
// 팩토리 함수로 생성된 구체적인 GET definition을 전달합니다.
const { data, error, isPending } = useNexusQuery(usersDefinition.getById(id));
if (isPending && !data) return <p>Loading…</p>;
if (error) return <p>Error</p>;
return <pre>{JSON.stringify(data, null, 2)}</pre>;
}
팁
definition
(과 파라미터)이 캐시 키를 결정합니다. 서버에서 읽은 데이터는 하이드레이션을 통해 클라이언트에서 매끄럽게 재사용됩니다.- Next.js의 캐싱 동작과 연동하려면
definition
의server.tags/revalidate
와client.tags/revalidate
옵션을 설정하세요.
함께 보기: nexus, useNexusQuery, Definitions.
Last updated on