or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

tessl/npm-trpc--react-query

A tRPC wrapper around react-query that provides end-to-end typesafe APIs with React Query integration

Workspace
tessl
Visibility
Public
Created
Last updated
Describes
npmpkg:npm/@trpc/react-query@11.5.x

To install, run

npx @tessl/cli install tessl/npm-trpc--react-query@11.5.0

0

# tRPC React Query

1

2

tRPC React Query is a TypeScript-first React library that provides end-to-end typesafe APIs by integrating tRPC with TanStack React Query. It offers React hooks for queries, mutations, and subscriptions with automatic type inference from tRPC router definitions, built-in caching and background updates, and comprehensive support for server-side rendering.

3

4

## Package Information

5

6

- **Package Name**: @trpc/react-query

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install @trpc/react-query @tanstack/react-query`

10

11

## Core Imports

12

13

Main client-side imports:

14

15

```typescript

16

import { createTRPCReact } from "@trpc/react-query";

17

import type { AppRouter } from "./server";

18

19

export const trpc = createTRPCReact<AppRouter>();

20

```

21

22

Server-side helpers:

23

24

```typescript

25

import { createServerSideHelpers } from "@trpc/react-query/server";

26

```

27

28

React Server Components (RSC) support:

29

30

```typescript

31

import { createHydrationHelpers } from "@trpc/react-query/rsc";

32

```

33

34

Query utilities:

35

36

```typescript

37

import { getQueryKey, getMutationKey, createTRPCQueryUtils } from "@trpc/react-query";

38

```

39

40

For CommonJS:

41

42

```javascript

43

const { createTRPCReact } = require("@trpc/react-query");

44

const { createServerSideHelpers } = require("@trpc/react-query/server");

45

```

46

47

## Basic Usage

48

49

```typescript

50

import { createTRPCReact } from "@trpc/react-query";

51

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

52

import type { AppRouter } from "./server";

53

54

// Create tRPC React hooks

55

export const trpc = createTRPCReact<AppRouter>();

56

57

// Provider setup

58

export function App() {

59

const [queryClient] = useState(() => new QueryClient());

60

const [trpcClient] = useState(() =>

61

trpc.createClient({

62

url: "http://localhost:5000/trpc",

63

})

64

);

65

66

return (

67

<trpc.Provider client={trpcClient} queryClient={queryClient}>

68

<QueryClientProvider client={queryClient}>

69

<MyComponent />

70

</QueryClientProvider>

71

</trpc.Provider>

72

);

73

}

74

75

// Component usage

76

function MyComponent() {

77

const { data, error, status } = trpc.greeting.useQuery({ name: "tRPC" });

78

const mutation = trpc.updateUser.useMutation();

79

80

if (error) return <p>{error.message}</p>;

81

if (status !== "success") return <p>Loading...</p>;

82

83

return <div>{data && <p>{data.greeting}</p>}</div>;

84

}

85

```

86

87

## Architecture

88

89

tRPC React Query is built around several key components:

90

91

- **Hook Factory**: `createTRPCReact` generates typed React hooks based on your tRPC router schema

92

- **Provider System**: React context provider that manages client configuration and query client state

93

- **Procedure Hooks**: Dynamically generated hooks (useQuery, useMutation, useSubscription) that mirror your tRPC router structure

94

- **Utility Functions**: Query manipulation utilities available via `useUtils()` for cache management and imperative operations

95

- **Type System**: Complete TypeScript inference from server router to client hooks with compile-time validation

96

- **SSR/RSC Support**: Server-side helpers for data prefetching and hydration in Next.js and other frameworks

97

98

## Capabilities

99

100

### Hook Creation

101

102

Core factory function that creates typed React hooks from your tRPC router definition.

103

104

```typescript { .api }

105

function createTRPCReact<TRouter extends AnyRouter, TSSRContext = unknown>(

106

opts?: CreateTRPCReactOptions<TRouter>

107

): CreateTRPCReact<TRouter, TSSRContext>;

108

109

interface CreateTRPCReact<TRouter extends AnyRouter, TSSRContext> {

110

Provider: TRPCProvider<TRouter, TSSRContext>;

111

createClient: typeof createTRPCClient<TRouter>;

112

useUtils(): CreateReactUtils<TRouter, TSSRContext>;

113

useQueries: TRPCUseQueries<TRouter>;

114

useSuspenseQueries: TRPCUseSuspenseQueries<TRouter>;

115

// Dynamic router-based hooks are automatically generated

116

}

117

```

118

119

[Hook Creation](./hook-creation.md)

120

121

### Query Hooks

122

123

React hooks for data fetching with caching, background updates, and type safety.

124

125

```typescript { .api }

126

// Generated for each query procedure in your router

127

procedure.useQuery(input: TInput, opts?: UseTRPCQueryOptions): UseTRPCQueryResult<TData, TError>;

128

procedure.useSuspenseQuery(input: TInput, opts?: UseTRPCSuspenseQueryOptions): [TData, UseSuspenseQueryResult];

129

procedure.useInfiniteQuery(input: TInput, opts?: UseTRPCInfiniteQueryOptions): UseTRPCInfiniteQueryResult<TData, TError>;

130

procedure.useSuspenseInfiniteQuery(input: TInput, opts?: UseTRPCSuspenseInfiniteQueryOptions): [TData, UseSuspenseInfiniteQueryResult];

131

```

132

133

[Query Hooks](./query-hooks.md)

134

135

### Mutation Hooks

136

137

React hooks for data modifications with optimistic updates and error handling.

138

139

```typescript { .api }

140

// Generated for each mutation procedure in your router

141

procedure.useMutation<TContext = unknown>(

142

opts?: UseTRPCMutationOptions<TInput, TError, TOutput, TContext>

143

): UseTRPCMutationResult<TOutput, TError, TInput, TContext>;

144

```

145

146

[Mutation Hooks](./mutation-hooks.md)

147

148

### Subscription Hooks

149

150

React hooks for real-time data subscriptions with automatic connection management.

151

152

```typescript { .api }

153

// Generated for each subscription procedure in your router

154

procedure.useSubscription(

155

input: TInput,

156

opts?: UseTRPCSubscriptionOptions<TOutput, TError>

157

): TRPCSubscriptionResult<TOutput, TError>;

158

```

159

160

[Subscription Hooks](./subscription-hooks.md)

161

162

### Query Utilities

163

164

Comprehensive utility functions for imperative query operations and cache management.

165

166

```typescript { .api }

167

interface CreateReactUtils<TRouter, TSSRContext> {

168

// Query manipulation

169

invalidate(input?: TInput, opts?: InvalidateOptions): Promise<void>;

170

refetch(input?: TInput, opts?: RefetchOptions): Promise<void>;

171

cancel(input?: TInput): Promise<void>;

172

173

// Data manipulation

174

setData(input: TInput, updater: Updater<TData>, opts?: SetDataOptions): void;

175

getData(input?: TInput): TData | undefined;

176

setInfiniteData(input: TInput, updater: Updater<InfiniteData<TData>>, opts?: SetDataOptions): void;

177

getInfiniteData(input?: TInput): InfiniteData<TData> | undefined;

178

179

// Imperative fetching

180

fetch(input: TInput, opts?: TRPCFetchQueryOptions): Promise<TData>;

181

fetchInfinite(input: TInput, opts?: TRPCFetchInfiniteQueryOptions): Promise<InfiniteData<TData>>;

182

prefetch(input: TInput, opts?: TRPCFetchQueryOptions): Promise<void>;

183

prefetchInfinite(input: TInput, opts?: TRPCFetchInfiniteQueryOptions): Promise<void>;

184

ensureData(input: TInput, opts?: TRPCFetchQueryOptions): Promise<TData>;

185

}

186

```

187

188

[Query Utilities](./query-utilities.md)

189

190

### Server-Side Helpers

191

192

Functions for server-side rendering and static generation.

193

194

```typescript { .api }

195

function createServerSideHelpers<TRouter extends AnyRouter>(

196

opts: CreateServerSideHelpersOptions<TRouter>

197

): ServerSideHelpers<TRouter>;

198

```

199

200

[Server-Side Helpers](./server-side-helpers.md)

201

202

### React Server Components (RSC)

203

204

Support for React Server Components with hydration helpers for Next.js App Router and similar frameworks.

205

206

```typescript { .api }

207

function createHydrationHelpers<TRouter extends AnyRouter>(

208

caller: Caller<TRouter>,

209

getQueryClient: () => QueryClient

210

): { trpc: DecoratedCaller<TRouter>; HydrateClient: React.ComponentType };

211

```

212

213

[React Server Components](./react-server-components.md)

214

215

### Query Keys and Utilities

216

217

Utilities for working with React Query keys and mutations in the tRPC context.

218

219

```typescript { .api }

220

function getQueryKey<TProcedureOrRouter extends ProcedureOrRouter>(

221

procedureOrRouter: TProcedureOrRouter,

222

...params: GetParams<TProcedureOrRouter>

223

): TRPCQueryKey;

224

225

function getMutationKey<TProcedure extends DecoratedMutation<any>>(

226

procedure: TProcedure

227

): TRPCMutationKey;

228

229

function createTRPCQueryUtils<TRouter extends AnyRouter>(

230

opts: CreateQueryUtilsOptions<TRouter>

231

): TRPCQueryUtils<TRouter>;

232

```

233

234

[Query Keys and Utilities](./query-keys.md)

235

236

## Types

237

238

```typescript { .api }

239

type CreateTRPCReactOptions<TRouter extends AnyRouter> = {

240

context?: React.Context<any>;

241

overrides?: {

242

useMutation?: {

243

onSuccess?: (options: { originalFn: () => void }) => void;

244

};

245

};

246

};

247

248

type TRPCQueryKey = [

249

readonly string[],

250

{ input?: unknown; type?: Exclude<QueryType, 'any'> }?

251

];

252

253

type TRPCMutationKey = [readonly string[]];

254

255

type QueryType = 'any' | 'infinite' | 'query';

256

257

interface TRPCReactRequestOptions extends Omit<TRPCRequestOptions, 'signal'> {

258

ssr?: boolean;

259

abortOnUnmount?: boolean;

260

}

261

262

interface TRPCProvider<TRouter extends AnyRouter, TSSRContext> {

263

(props: TRPCProviderProps<TRouter, TSSRContext>): JSX.Element;

264

}

265

266

interface TRPCProviderProps<TRouter extends AnyRouter, TSSRContext> {

267

client: TRPCClient<TRouter> | TRPCUntypedClient<TRouter>;

268

queryClient: QueryClient;

269

ssrContext?: TSSRContext;

270

ssrState?: SSRState;

271

abortOnUnmount?: boolean;

272

children: ReactNode;

273

}

274

```