0
# Hook Creation
1
2
The core functionality of @trpc/react-query revolves around the `createTRPCReact` factory function that generates typed React hooks from your tRPC router definition.
3
4
## Capabilities
5
6
### createTRPCReact
7
8
Creates a complete set of typed React hooks and utilities for your tRPC router.
9
10
```typescript { .api }
11
/**
12
* Creates typed React hooks for tRPC procedures based on your router schema
13
* @param opts - Optional configuration for the hook factory
14
* @returns Object containing Provider, hooks, and utilities
15
*/
16
function createTRPCReact<TRouter extends AnyRouter, TSSRContext = unknown>(
17
opts?: CreateTRPCReactOptions<TRouter>
18
): CreateTRPCReact<TRouter, TSSRContext>;
19
20
interface CreateTRPCReactOptions<TRouter extends AnyRouter> {
21
/** Custom React context for tRPC provider */
22
context?: React.Context<any>;
23
/** Abort all queries when unmounting @default false */
24
abortOnUnmount?: boolean;
25
/** Hook behavior overrides */
26
overrides?: {
27
useMutation?: Partial<UseMutationOverride>;
28
};
29
}
30
31
interface UseMutationOverride {
32
onSuccess: (opts: {
33
/** Calls the original function that was defined in the query's onSuccess option */
34
originalFn: () => MaybePromise<void>;
35
queryClient: QueryClient;
36
/** Meta data passed in from the useMutation() hook */
37
meta: Record<string, unknown>;
38
}) => MaybePromise<void>;
39
}
40
41
interface CreateTRPCReact<TRouter extends AnyRouter, TSSRContext> {
42
/** React context provider component */
43
Provider: TRPCProvider<TRouter, TSSRContext>;
44
/** Factory function for creating tRPC clients */
45
createClient: typeof createTRPCClient<TRouter>;
46
/** Hook for accessing query utilities */
47
useUtils(): CreateReactUtils<TRouter, TSSRContext>;
48
/** @deprecated Use useUtils instead */
49
useContext(): CreateReactUtils<TRouter, TSSRContext>;
50
/** Hook for batch queries */
51
useQueries: TRPCUseQueries<TRouter>;
52
/** Hook for batch suspense queries */
53
useSuspenseQueries: TRPCUseSuspenseQueries<TRouter>;
54
55
// Dynamic router-based hooks are automatically generated based on your router structure
56
// For example, if your router has:
57
// - router.user.get (query) -> trpc.user.get.useQuery()
58
// - router.user.create (mutation) -> trpc.user.create.useMutation()
59
// - router.notifications.subscribe (subscription) -> trpc.notifications.subscribe.useSubscription()
60
}
61
```
62
63
**Usage Examples:**
64
65
```typescript
66
import { createTRPCReact } from "@trpc/react-query";
67
import type { AppRouter } from "./server";
68
69
// Basic usage
70
export const trpc = createTRPCReact<AppRouter>();
71
72
// With custom context
73
const MyTRPCContext = React.createContext(null);
74
export const trpc = createTRPCReact<AppRouter>({
75
context: MyTRPCContext,
76
});
77
78
// With mutation overrides
79
export const trpc = createTRPCReact<AppRouter>({
80
overrides: {
81
useMutation: {
82
onSuccess: ({ originalFn }) => {
83
// Custom success behavior
84
console.log("Mutation succeeded");
85
originalFn();
86
},
87
},
88
},
89
});
90
```
91
92
### TRPCProvider
93
94
React context provider that manages tRPC client configuration and React Query state.
95
96
```typescript { .api }
97
/**
98
* Provider component that supplies tRPC client and query client to child components
99
*/
100
interface TRPCProvider<TRouter extends AnyRouter, TSSRContext> {
101
(props: TRPCProviderProps<TRouter, TSSRContext>): JSX.Element;
102
}
103
104
interface TRPCProviderProps<TRouter extends AnyRouter, TSSRContext> {
105
/** tRPC client instance */
106
client: TRPCClient<TRouter> | TRPCUntypedClient<TRouter>;
107
/** React Query client instance */
108
queryClient: QueryClient;
109
/** Server-side rendering context */
110
ssrContext?: TSSRContext;
111
/** SSR state for hydration */
112
ssrState?: SSRState;
113
/** Whether to abort requests on component unmount */
114
abortOnUnmount?: boolean;
115
/** Child components */
116
children: ReactNode;
117
}
118
119
type SSRState = false | 'prepass' | 'mounting' | 'mounted';
120
```
121
122
**Usage Examples:**
123
124
```typescript
125
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
126
import { trpc } from "./utils/trpc";
127
128
function App() {
129
const [queryClient] = useState(() => new QueryClient());
130
const [trpcClient] = useState(() =>
131
trpc.createClient({
132
url: "http://localhost:5000/trpc",
133
})
134
);
135
136
return (
137
<trpc.Provider client={trpcClient} queryClient={queryClient}>
138
<QueryClientProvider client={queryClient}>
139
<MyApp />
140
</QueryClientProvider>
141
</trpc.Provider>
142
);
143
}
144
145
// With SSR context
146
function AppWithSSR({ ssrContext }: { ssrContext: MySSRContext }) {
147
return (
148
<trpc.Provider
149
client={trpcClient}
150
queryClient={queryClient}
151
ssrContext={ssrContext}
152
ssrState="mounting"
153
>
154
<MyApp />
155
</trpc.Provider>
156
);
157
}
158
```
159
160
### Dynamic Hook Generation
161
162
The `createTRPCReact` function automatically generates hooks based on your router structure. Each procedure gets decorated with appropriate hook methods:
163
164
```typescript { .api }
165
// For query procedures
166
interface QueryProcedureHooks<TInput, TOutput, TError> {
167
useQuery(input: TInput, opts?: UseTRPCQueryOptions): UseTRPCQueryResult<TOutput, TError>;
168
useSuspenseQuery(input: TInput, opts?: UseTRPCSuspenseQueryOptions): [TOutput, UseSuspenseQueryResult];
169
usePrefetchQuery(input: TInput, opts?: TRPCFetchQueryOptions): void;
170
171
// If procedure supports cursor/pagination
172
useInfiniteQuery?(input: TInput, opts?: UseTRPCInfiniteQueryOptions): UseTRPCInfiniteQueryResult<TOutput, TError>;
173
useSuspenseInfiniteQuery?(input: TInput, opts?: UseTRPCSuspenseInfiniteQueryOptions): [InfiniteData<TOutput>, UseSuspenseInfiniteQueryResult];
174
usePrefetchInfiniteQuery?(input: TInput, opts?: TRPCFetchInfiniteQueryOptions): void;
175
}
176
177
// For mutation procedures
178
interface MutationProcedureHooks<TInput, TOutput, TError> {
179
useMutation<TContext = unknown>(
180
opts?: UseTRPCMutationOptions<TInput, TError, TOutput, TContext>
181
): UseTRPCMutationResult<TOutput, TError, TInput, TContext>;
182
}
183
184
// For subscription procedures
185
interface SubscriptionProcedureHooks<TInput, TOutput, TError> {
186
useSubscription(
187
input: TInput,
188
opts?: UseTRPCSubscriptionOptions<TOutput, TError>
189
): TRPCSubscriptionResult<TOutput, TError>;
190
}
191
```
192
193
**Usage Examples:**
194
195
```typescript
196
// Assuming your router has these procedures:
197
// router.user.get (query)
198
// router.user.create (mutation)
199
// router.posts.list (query with cursor)
200
// router.notifications.subscribe (subscription)
201
202
function MyComponent() {
203
// Query hook
204
const { data: user } = trpc.user.get.useQuery({ id: 1 });
205
206
// Mutation hook
207
const createUser = trpc.user.create.useMutation();
208
209
// Infinite query hook (for cursor-based pagination)
210
const {
211
data: posts,
212
fetchNextPage,
213
hasNextPage
214
} = trpc.posts.list.useInfiniteQuery(
215
{ limit: 10 },
216
{
217
getNextPageParam: (lastPage) => lastPage.nextCursor,
218
}
219
);
220
221
// Subscription hook
222
const { data: notification } = trpc.notifications.subscribe.useSubscription({
223
userId: 1,
224
});
225
226
return (
227
<div>
228
<h1>{user?.name}</h1>
229
<button onClick={() => createUser.mutate({ name: "New User" })}>
230
Create User
231
</button>
232
</div>
233
);
234
}
235
```
236
237
### Client Factory
238
239
Access to the tRPC client factory for creating configured client instances.
240
241
```typescript { .api }
242
/**
243
* Factory function for creating tRPC clients (re-exported from @trpc/client)
244
*/
245
createClient: typeof createTRPCClient<TRouter>;
246
```
247
248
**Usage Examples:**
249
250
```typescript
251
const trpcClient = trpc.createClient({
252
url: "http://localhost:5000/trpc",
253
headers: {
254
Authorization: "Bearer token",
255
},
256
});
257
258
// With transformers
259
const trpcClient = trpc.createClient({
260
url: "http://localhost:5000/trpc",
261
transformer: superjson,
262
});
263
```