or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

Files

docs

context.mderror-handling.mdindex.mdinfinite-queries.mdmutations.mdparallel-queries.mdqueries.mdssr.mdstatus.md

index.mddocs/

0

# React Query

1

2

React Query is a powerful data-fetching and state management library for React applications that provides hooks for fetching, caching, synchronizing and updating asynchronous and remote data. It eliminates the need for complex state management patterns when dealing with server state by offering intelligent caching with automatic background updates, optimistic updates, request deduplication, and built-in error handling.

3

4

## Package Information

5

6

- **Package Name**: react-query

7

- **Package Type**: npm

8

- **Language**: TypeScript

9

- **Installation**: `npm install react-query`

10

11

## Core Imports

12

13

```typescript

14

import { useQuery, useMutation, QueryClient, QueryClientProvider } from "react-query";

15

```

16

17

For CommonJS:

18

19

```javascript

20

const { useQuery, useMutation, QueryClient, QueryClientProvider } = require("react-query");

21

```

22

23

## Basic Usage

24

25

```typescript

26

import { useQuery, useMutation, QueryClient, QueryClientProvider } from "react-query";

27

28

// Create a query client

29

const queryClient = new QueryClient();

30

31

function App() {

32

return (

33

<QueryClientProvider client={queryClient}>

34

<UserProfile userId="123" />

35

</QueryClientProvider>

36

);

37

}

38

39

function UserProfile({ userId }: { userId: string }) {

40

// Fetch user data

41

const { data: user, isLoading, error } = useQuery({

42

queryKey: ['user', userId],

43

queryFn: () => fetch(`/api/users/${userId}`).then(res => res.json())

44

});

45

46

// Create a mutation for updating user

47

const updateUser = useMutation({

48

mutationFn: (userData: any) =>

49

fetch(`/api/users/${userId}`, {

50

method: 'PUT',

51

body: JSON.stringify(userData)

52

}),

53

onSuccess: () => {

54

// Invalidate and refetch user data

55

queryClient.invalidateQueries({ queryKey: ['user', userId] });

56

}

57

});

58

59

if (isLoading) return <div>Loading...</div>;

60

if (error) return <div>Error loading user</div>;

61

62

return (

63

<div>

64

<h1>{user.name}</h1>

65

<button onClick={() => updateUser.mutate({ name: 'New Name' })}>

66

Update Name

67

</button>

68

</div>

69

);

70

}

71

```

72

73

## Architecture

74

75

React Query is built around several key components:

76

77

- **QueryClient**: Central client managing all queries and mutations, with intelligent caching and invalidation

78

- **Hooks**: React hooks (`useQuery`, `useMutation`, etc.) providing reactive data fetching with automatic re-renders

79

- **Context System**: Provider pattern allowing QueryClient sharing across component trees

80

- **Observers**: Internal observer pattern for tracking query state changes and coordinating updates

81

- **Cache Management**: Sophisticated caching with background refetching, stale-while-revalidate patterns, and automatic garbage collection

82

- **SSR Support**: Complete server-side rendering support with hydration and dehydration utilities

83

84

## Capabilities

85

86

### Query Operations

87

88

Core data fetching functionality with intelligent caching, background updates, and automatic error handling. Perfect for loading data from APIs with automatic retry and stale-while-revalidate patterns.

89

90

```typescript { .api }

91

function useQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(

92

options: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>

93

): UseQueryResult<TData, TError>;

94

95

function useQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(

96

queryKey: TQueryKey,

97

queryFn: QueryFunction<TQueryFnData, TQueryKey>,

98

options?: UseQueryOptions<TQueryFnData, TError, TData, TQueryKey>

99

): UseQueryResult<TData, TError>;

100

```

101

102

[Query Operations](./queries.md)

103

104

### Infinite Queries

105

106

Specialized query hook for paginated data with infinite scrolling support, automatic page management, and cursor-based pagination.

107

108

```typescript { .api }

109

function useInfiniteQuery<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey>(

110

options: UseInfiniteQueryOptions<TQueryFnData, TError, TData, TQueryFnData, TQueryKey>

111

): UseInfiniteQueryResult<TData, TError>;

112

113

interface UseInfiniteQueryResult<TData = unknown, TError = unknown> {

114

data: InfiniteData<TData> | undefined;

115

fetchNextPage: () => Promise<any>;

116

fetchPreviousPage: () => Promise<any>;

117

hasNextPage: boolean;

118

hasPreviousPage: boolean;

119

isFetchingNextPage: boolean;

120

isFetchingPreviousPage: boolean;

121

}

122

```

123

124

[Infinite Queries](./infinite-queries.md)

125

126

### Parallel Queries

127

128

Execute multiple queries in parallel with type-safe results and coordinated loading states.

129

130

```typescript { .api }

131

function useQueries<T extends any[]>({

132

queries,

133

context,

134

}: {

135

queries: readonly [...QueriesOptions<T>];

136

context?: React.Context<QueryClient | undefined>;

137

}): QueriesResults<T>;

138

```

139

140

[Parallel Queries](./parallel-queries.md)

141

142

### Mutations

143

144

Data mutation operations with optimistic updates, automatic error handling, and cache invalidation patterns.

145

146

```typescript { .api }

147

function useMutation<TData = unknown, TError = unknown, TVariables = void, TContext = unknown>(

148

options: UseMutationOptions<TData, TError, TVariables, TContext>

149

): UseMutationResult<TData, TError, TVariables, TContext>;

150

151

interface UseMutationResult<TData = unknown, TError = unknown, TVariables = unknown, TContext = unknown> {

152

mutate: (variables: TVariables, options?: MutateOptions<TData, TError, TVariables, TContext>) => void;

153

mutateAsync: (variables: TVariables, options?: MutateOptions<TData, TError, TVariables, TContext>) => Promise<TData>;

154

data: TData | undefined;

155

error: TError | null;

156

isError: boolean;

157

isPending: boolean;

158

isSuccess: boolean;

159

}

160

```

161

162

[Mutations](./mutations.md)

163

164

### Context & Client Management

165

166

QueryClient provider system for sharing client instances across component trees with context isolation and configuration.

167

168

```typescript { .api }

169

function QueryClientProvider(props: QueryClientProviderProps): JSX.Element;

170

function useQueryClient(options?: ContextOptions): QueryClient;

171

172

interface QueryClientProviderProps {

173

client: QueryClient;

174

children?: React.ReactNode;

175

context?: React.Context<QueryClient | undefined>;

176

contextSharing?: boolean;

177

}

178

```

179

180

[Context & Client Management](./context.md)

181

182

### Status Monitoring

183

184

Hooks for monitoring global query and mutation states across the application.

185

186

```typescript { .api }

187

function useIsFetching(filters?: QueryFilters, options?: ContextOptions): number;

188

function useIsMutating(filters?: MutationFilters, options?: ContextOptions): number;

189

```

190

191

[Status Monitoring](./status.md)

192

193

### SSR & Hydration

194

195

Server-side rendering support with state dehydration and hydration for seamless SSR/SSG integration.

196

197

```typescript { .api }

198

function useHydrate(state: unknown, options?: HydrateOptions & ContextOptions): void;

199

function Hydrate(props: HydrateProps): React.ReactElement;

200

function IsRestoringProvider(props: { value: boolean; children: React.ReactNode; }): React.ReactElement;

201

function useIsRestoring(): boolean;

202

203

interface HydrateProps {

204

state?: unknown;

205

options?: HydrateOptions;

206

children?: React.ReactNode;

207

}

208

```

209

210

[SSR & Hydration](./ssr.md)

211

212

### Error Handling

213

214

Error boundary integration and reset functionality for graceful error recovery.

215

216

```typescript { .api }

217

function QueryErrorResetBoundary(props: QueryErrorResetBoundaryProps): JSX.Element;

218

function useQueryErrorResetBoundary(): QueryErrorResetBoundaryValue;

219

220

interface QueryErrorResetBoundaryValue {

221

clearReset: () => void;

222

isReset: () => boolean;

223

reset: () => void;

224

}

225

```

226

227

[Error Handling](./error-handling.md)

228

229

## Core Types

230

231

```typescript { .api }

232

type QueryKey = readonly unknown[];

233

234

type QueryFunction<T = unknown, TQueryKey extends QueryKey = QueryKey> = (

235

context: QueryFunctionContext<TQueryKey>

236

) => T | Promise<T>;

237

238

interface QueryFunctionContext<TQueryKey extends QueryKey = QueryKey> {

239

queryKey: TQueryKey;

240

signal?: AbortSignal;

241

pageParam?: unknown;

242

meta: QueryMeta | undefined;

243

}

244

245

interface UseQueryResult<TData = unknown, TError = unknown> {

246

data: TData | undefined;

247

error: TError | null;

248

isError: boolean;

249

isLoading: boolean;

250

isPending: boolean;

251

isSuccess: boolean;

252

isFetching: boolean;

253

isRefetching: boolean;

254

status: 'pending' | 'error' | 'success';

255

fetchStatus: 'fetching' | 'paused' | 'idle';

256

refetch: () => Promise<any>;

257

}

258

259

interface DefinedUseQueryResult<TData = unknown, TError = unknown> extends Omit<UseQueryResult<TData, TError>, 'data'> {

260

data: TData;

261

}

262

263

interface UseQueryOptions<TQueryFnData = unknown, TError = unknown, TData = TQueryFnData, TQueryKey extends QueryKey = QueryKey> {

264

queryKey?: TQueryKey;

265

queryFn?: QueryFunction<TQueryFnData, TQueryKey>;

266

enabled?: boolean;

267

retry?: boolean | number | ((failureCount: number, error: TError) => boolean);

268

retryDelay?: number | ((retryAttempt: number, error: TError) => number);

269

staleTime?: number;

270

cacheTime?: number;

271

refetchInterval?: number | false | ((data: TData | undefined, query: Query) => number | false);

272

refetchIntervalInBackground?: boolean;

273

refetchOnMount?: boolean | "always";

274

refetchOnWindowFocus?: boolean | "always";

275

refetchOnReconnect?: boolean | "always";

276

select?: (data: TQueryFnData) => TData;

277

initialData?: TData | (() => TData);

278

placeholderData?: TData | (() => TData);

279

onSuccess?: (data: TData) => void;

280

onError?: (error: TError) => void;

281

onSettled?: (data: TData | undefined, error: TError | null) => void;

282

context?: React.Context<QueryClient | undefined>;

283

}

284

285

interface InfiniteData<TData> {

286

pages: TData[];

287

pageParams: unknown[];

288

}

289

290

type QueryFilters = {

291

queryKey?: QueryKey;

292

exact?: boolean;

293

type?: 'active' | 'inactive' | 'all';

294

stale?: boolean;

295

fetching?: boolean;

296

};

297

298

type MutationFilters = {

299

mutationKey?: QueryKey;

300

exact?: boolean;

301

type?: 'active' | 'paused' | 'all';

302

};

303

304

interface ContextOptions {

305

context?: React.Context<QueryClient | undefined>;

306

}

307

```