メインコンテンツへスキップ
バージョン: 11.x

React Query インテグレーション (Classic)

非公式ベータ版翻訳

このページは PageTurner AI で翻訳されました(ベータ版)。プロジェクト公式の承認はありません。 エラーを見つけましたか? 問題を報告 →

ヒント

これは React Query の「Classic」インテグレーションに関するドキュメントです(現在もサポートは継続していますが)。新規の tRPC プロジェクトを TanStack React Query で始める場合、推奨される方法ではありません。代わりに新しい 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.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
 
export const trpc = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'YOUR_API_URL' })],
});
utils/trpc.ts
ts
import { createTRPCClient, httpBatchLink } from '@trpc/client';
import type { AppRouter } from '../server';
 
export const trpc = createTRPCClient<AppRouter>({
links: [httpBatchLink({ url: 'YOUR_API_URL' })],
});
components/PostList.tsx
tsx
import { useQuery } from '@tanstack/react-query';
import { trpc } from '../utils/trpc';
 
function PostList() {
const { data } = useQuery({
queryKey: ['posts'],
queryFn: () => trpc.post.list.query(),
});
data; // Post[]
 
// ...
}
components/PostList.tsx
tsx
import { useQuery } from '@tanstack/react-query';
import { trpc } from '../utils/trpc';
 
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 の一部の側面を抽象化します:

  • クエリキー - 手続きの入力値に基づいて、tRPC が自動的に生成・管理します

    • tRPC が算出したクエリキーが必要な場合は getQueryKey を使用できます
  • デフォルトの型安全性 - tRPC バックエンドで提供した型が React Query クライアントの型にも反映され、React アプリ全体で安全性が確保されます