React Query 통합 (클래식)
이 페이지는 PageTurner AI로 번역되었습니다(베타). 프로젝트 공식 승인을 받지 않았습니다. 오류를 발견하셨나요? 문제 신고 →
이 문서는 '클래식' React Query 통합에 대한 설명입니다. (여전히 지원되지만) TanStack React Query로 새로운 tRPC 프로젝트를 시작할 때 권장하는 방식은 아닙니다. 대신 새로운 TanStack React Query 통합을 사용하길 권장합니다.
tRPC는 React와의 일류 통합을 제공합니다. 내부적으로는 매우 인기 있는 @tanstack/react-query를 래핑한 것이므로, React Query의 사용법에 대해 더 깊이 알고 싶다면 해당 문서를 숙지하는 것을 권장합니다.
Next.js를 사용 중이라면, 대신 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.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from '../server';export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'YOUR_API_URL' })],});
utils/trpc.tstsimport {createTRPCClient ,httpBatchLink } from '@trpc/client';import type {AppRouter } from '../server';export consttrpc =createTRPCClient <AppRouter >({links : [httpBatchLink ({url : 'YOUR_API_URL' })],});
components/PostList.tsxtsximport {useQuery } from '@tanstack/react-query';import {trpc } from '../utils/trpc';functionPostList () {const {data } =useQuery ({queryKey : ['posts'],queryFn : () =>trpc .post .list .query (),});data ; // Post[]// ...}
components/PostList.tsxtsximport {useQuery } from '@tanstack/react-query';import {trpc } from '../utils/trpc';functionPostList () {const {data } =useQuery ({queryKey : ['posts'],queryFn : () =>trpc .post .list .query (),});data ; // Post[]// ...}
tRPC React Query 통합
이 라이브러리를 사용하면 React 컴포넌트 내에서 직접 사용할 수 있습니다.
pages/IndexPage.tsxtsximport {trpc } from '../utils/trpc';export default functionIndexPage () {consthelloQuery =trpc .hello .useQuery ({name : 'Bob' });constgoodbyeMutation =trpc .goodbye .useMutation ();return (<div ><p >{helloQuery .data ?.greeting }</p ><button onClick ={() =>goodbyeMutation .mutate ()}>Say Goodbye</button ></div >);}
pages/IndexPage.tsxtsximport {trpc } from '../utils/trpc';export default functionIndexPage () {consthelloQuery =trpc .hello .useQuery ({name : 'Bob' });constgoodbyeMutation =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 애플리케이션 전체에 걸쳐 안전성이 보장됩니다