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

React와 함께 사용하기

비공식 베타 번역

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

정보
  • Next.js를 사용 중이라면 Next.js 사용법 가이드를 참조하세요.
  • Node.js 백엔드에서 타입을 추론하려면 프론트엔드와 백엔드를 동일 모노레포에 두어야 합니다.

기존 React 프로젝트에 tRPC 추가하기

서버 측

1. 의존성 설치

bash
yarn add @trpc/server zod
bash
yarn add @trpc/server zod
  • Zod: 대부분의 예제는 입력 검증을 위해 Zod를 사용하며 권장하지만 필수는 아닙니다. 선호하는 검증 라이브러리(Yup, Superstruct, io-ts 등)를 사용할 수 있습니다. 실제로 parse, create 또는 validateSync 메서드를 포함하는 모든 객체가 작동합니다.

2. 엄격 모드 활성화

Zod를 입력 유효성 검사에 사용하려면 tsconfig.json에서 엄격 모드를 활성화해야 합니다:

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strict": true
}
}

엄격 모드가 부담스러울 경우 최소한 strictNullChecks는 활성화하세요:

json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}
json
// tsconfig.json
{
// ...
"compilerOptions": {
// ...
"strictNullChecks": true
}
}

3. appRouter 구현

퀵스타트를 따라가고 @trpc/server 문서를 참조하세요. API를 구현하고 HTTP를 통해 리스닝 중인 상태가 되면 다음 단계로 진행하세요.

클라이언트 측

tRPC는 Create React App과 완벽하게 호환됩니다!

1. 의존성 설치

bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
bash
yarn add @trpc/client @trpc/server @trpc/react react-query@3
  • @trpc/server: @trpc/client의 피어 의존성이므로 다시 설치해야 합니다!

  • Tanstack의 React Query: @trpc/react는 @tanstack/react-query를 감싼 씬 래퍼를 제공합니다. 피어 의존성으로 필요합니다.

2. tRPC 훅 생성

createReactQueryHooks를 사용해 AppRouter 타입 시그니처에서 강력한 타입의 React 훅 세트를 생성하세요.

utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}
utils/trpc.ts
tsx
// utils/trpc.ts
import { createReactQueryHooks } from '@trpc/react';
import type { AppRouter } from '../path/to/router.ts';
export const trpc = createReactQueryHooks<AppRouter>();
// => { useQuery: ..., useMutation: ...}

3. tRPC 프로바이더 추가

App.tsx에서:

App.tsx
tsx
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
App.tsx
tsx
import React, { useState } from 'react';
import { QueryClient, QueryClientProvider } from 'react-query';
import { trpc } from './utils/trpc';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
// optional
headers() {
return {
authorization: getAuthCookie(),
};
},
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}

4. 데이터 가져오기

pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const hello = trpc.useQuery(['hello', { text: 'client' }]);
if (!hello.data) return <div>Loading...</div>;
return (
<div>
<p>{hello.data.greeting}</p>
</div>
);
}
pages/IndexPage.tsx
tsx
import { trpc } from '../utils/trpc';
export default function IndexPage() {
const hello = trpc.useQuery(['hello', { text: 'client' }]);
if (!hello.data) return <div>Loading...</div>;
return (
<div>
<p>{hello.data.greeting}</p>
</div>
);
}