본문 바로가기
버전: 11.x

React Query 통합 (클래식)

비공식 베타 번역

이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →

이 문서는 '클래식' React Query 통합에 대한 설명입니다. (여전히 지원되지만) TanStack React Query로 새로운 tRPC 프로젝트를 시작할 때 권장하는 방식은 아닙니다. 대신 새로운 TanStack React Query 통합을 사용하길 권장합니다.

tRPC는 React와의 최고 수준 통합을 제공합니다. 내부적으로 이는 매우 인기 있는 @tanstack/react-query를 래핑한 것이므로, React Query의 문서가 사용법을 훨씬 더 깊이 있게 다루고 있기 때문에 해당 문서를 숙지하길 권장합니다.

Next.js를 사용 중이라면 해당 프레임워크와의 통합을 사용하길 권장합니다.

❓ Do I have to use an integration?

No! The integration is fully optional. You can use @tanstack/react-query using just a vanilla tRPC client, although then you'll have to manually manage query keys and do not get the same level of DX as when using the integration package.

utils/trpc.ts
ts
export const trpc = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'YOUR_API_URL' })],
});
utils/trpc.ts
ts
export const trpc = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'YOUR_API_URL' })],
});
components/PostList.tsx
tsx
function PostList() {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: () => trpc.post.list.query(),
});
data; // Post[]
// ...
}
components/PostList.tsx
tsx
function PostList() {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: () => trpc.post.list.query(),
});
data; // Post[]
// ...
}

tRPC React Query 통합

이 라이브러리는 React 컴포넌트 내에서 직접 사용할 수 있도록 합니다.

pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const helloQuery = trpc.hello.useQuery({ name: 'Bob' });
const goodbyeMutation = trpc.goodbye.useMutation();
return (
<div>
<p>{helloQuery.data?.greeting}</p>
<button onClick={() => goodbyeMutation.mutate()}>Say Goodbye</button>
</div>
);
}
pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const helloQuery = trpc.hello.useQuery({ name: 'Bob' });
const goodbyeMutation = trpc.goodbye.useMutation();
return (
<div>
<p>{helloQuery.data?.greeting}</p>
<button onClick={() => goodbyeMutation.mutate()}>Say Goodbye</button>
</div>
);
}

순수 React Query와의 차이점

이 래퍼는 React Query의 일부 측면을 추상화합니다:

  • Query Keys - tRPC가 제공하는 프로시저 입력을 기반으로 자동 생성 및 관리됩니다

    • tRPC가 계산한 쿼리 키가 필요하다면 getQueryKey를 사용할 수 있습니다
  • 기본 타입 안전성 - tRPC 백엔드에서 제공한 타입이 React Query 클라이언트의 타입을 결정하므로 React 애플리케이션 전체에 걸쳐 안전성이 보장됩니다