Course contentsShow
← React
Lesson 1815 of 2,39642. Data Fetching LibrariesFree lesson

Using tRPC Queries in React Components

Calling trpc.user.list.useQuery() and other procedures; leveraging automatic type inference for response data and errors.

Using tRPC Queries in React Components

What you'll learn: How to call tRPC procedures in your React components and leverage automatic TypeScript inference for complete type safety.

The Magic Connection

With your tRPC router defined on the server, calling those procedures from React feels like invoking local functions—except they're fully typed API calls. You use hooks like trpc.user.list.useQuery() that mirror your server's router structure exactly.

The Basic Pattern

import { trpc } from './utils/trpc';

function UserList() {
  const { data, isLoading, error } = trpc.user.list.useQuery();

  if (isLoading) return <div>Loading users...</div>;
  if (error) return <div>Error: {error.message}</div>;

  return (
    <ul>
      {data.map(user => (
        <li key={user.id}>{user.name}</li>
      ))}
    </ul>
  );
}

Notice how data is automatically typed based on your server's return type. No manual TypeScript annotations needed. If your server returns User[], data knows it's User[] | undefined.

Queries with Input

function UserProfile({ userId }: { userId: string }) {
  const { data: user } = trpc.user.getById.useQuery({ id: userId });
  
  // TypeScript knows exactly what shape 'user' has
  return <h1>{user?.name}</h1>;
}

The input object { id: userId } is type-checked against your server's input schema. Pass the wrong shape? TypeScript catches it instantly.

Error Handling with Types

Even error is typed! tRPC errors include message, data, and error codes, all with proper TypeScript support:

if (error) {
  console.log(error.data?.code); // 'UNAUTHORIZED' | 'NOT_FOUND' | etc.
}

Key Takeaway: tRPC queries work like TanStack Query hooks but with full end-to-end type safety—your IDE knows exactly what each procedure accepts and returns, catching mistakes before runtime.