What is @trpc/react-query?
@trpc/react-query is a package that integrates tRPC with React Query, allowing you to create type-safe APIs and use them in your React applications with ease. It provides a seamless way to fetch, cache, and synchronize server data with your client-side state.
What are @trpc/react-query's main functionalities?
Type-safe API calls
This feature allows you to make type-safe API calls using tRPC and React Query. The `useQuery` hook fetches data from the server and provides loading and error states.
import { createReactQueryHooks } from '@trpc/react-query';
import { AppRouter } from './server/router';
const trpc = createReactQueryHooks<AppRouter>();
function MyComponent() {
const { data, error, isLoading } = trpc.useQuery(['getUser', { id: 1 }]);
if (isLoading) return <div>Loading...</div>;
if (error) return <div>Error: {error.message}</div>;
return <div>User: {data.name}</div>;
}
Mutations
This feature allows you to perform mutations, such as creating or updating data on the server. The `useMutation` hook provides methods to trigger the mutation and handle its result.
function MyComponent() {
const mutation = trpc.useMutation('createUser');
const handleCreateUser = async () => {
try {
await mutation.mutateAsync({ name: 'John Doe' });
alert('User created successfully');
} catch (error) {
alert('Error creating user: ' + error.message);
}
};
return <button onClick={handleCreateUser}>Create User</button>;
}
Optimistic Updates
This feature allows you to perform optimistic updates, where the UI is updated immediately while the mutation is being processed. The `onMutate`, `onError`, and `onSettled` callbacks help manage the optimistic update lifecycle.
function MyComponent() {
const queryClient = useQueryClient();
const mutation = trpc.useMutation('updateUser', {
onMutate: async (newData) => {
await queryClient.cancelQueries(['getUser', { id: newData.id }]);
const previousData = queryClient.getQueryData(['getUser', { id: newData.id }]);
queryClient.setQueryData(['getUser', { id: newData.id }], newData);
return { previousData };
},
onError: (err, newData, context) => {
queryClient.setQueryData(['getUser', { id: newData.id }], context.previousData);
},
onSettled: () => {
queryClient.invalidateQueries(['getUser', { id: newData.id }]);
}
});
const handleUpdateUser = async () => {
await mutation.mutateAsync({ id: 1, name: 'Jane Doe' });
};
return <button onClick={handleUpdateUser}>Update User</button>;
}
Other packages similar to @trpc/react-query
react-query
React Query is a powerful data-fetching library for React applications. It provides hooks for fetching, caching, and synchronizing server data with client-side state. Unlike @trpc/react-query, it does not provide built-in type safety or integration with tRPC.
apollo-client
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It offers features like caching, optimistic UI, and subscriptions. Unlike @trpc/react-query, it uses GraphQL instead of tRPC for API interactions.
swr
SWR (stale-while-revalidate) is a React Hooks library for data fetching developed by Vercel. It focuses on simplicity and performance, providing a lightweight solution for fetching and caching data. Unlike @trpc/react-query, it does not offer built-in type safety or integration with tRPC.
tRPC
End-to-end typesafe APIs made easy
@trpc/react-query
A tRPC wrapper around react-query.
Documentation
Full documentation for @trpc/react-query
can be found here
Installation
npm install @trpc/react-query@next @tanstack/react-query
yarn add @trpc/react-query@next @tanstack/react-query
pnpm add @trpc/react-query@next @tanstack/react-query
bun add @trpc/react-query@next @tanstack/react-query
Basic Example
Create a utils file that exports tRPC hooks and providers.
import { createTRPCReact } from '@trpc/react-query';
import type { AppRouter } from './server';
export const trpc = createTRPCReact<AppRouter>();
Use the provider to connect to your API.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
import { trpc } from '~/utils/trpc';
import React, { useState } from 'react';
export function App() {
const [queryClient] = useState(() => new QueryClient());
const [trpcClient] = useState(() =>
trpc.createClient({
url: 'http://localhost:5000/trpc',
}),
);
return (
<trpc.Provider client={trpcClient} queryClient={queryClient}>
<QueryClientProvider client={queryClient}>
{/* Your app here */}
</QueryClientProvider>
</trpc.Provider>
);
}
Now in any component, you can query your API using the proxy exported from the utils file.
import { trpc } from '~/utils/trpc';
export function Hello() {
const { data, error, status } = trpc.greeting.useQuery({ name: 'tRPC' });
if (error) {
return <p>{error.message}</p>;
}
if (status !== 'success') {
return <p>Loading...</p>;
}
return <div>{data && <p>{data.greeting}</p>}</div>;
}