Skip to main content

GraphQL

TanStack Query works seamlessly with GraphQL, providing powerful caching and state management for your GraphQL operations.
React Query’s fetching mechanisms are built on Promises, making it compatible with any asynchronous data fetching client, including GraphQL.

Why Use React Query with GraphQL?

While GraphQL clients like Apollo and Relay provide their own caching solutions, React Query offers:
  • Simpler API - Less boilerplate than traditional GraphQL clients
  • Framework agnostic - Works with any GraphQL client (graphql-request, urql, etc.)
  • Powerful DevTools - Visual cache inspection and debugging
  • Automatic refetching - Built-in window focus, network reconnect, and interval refetching
  • Optimistic updates - Easy-to-implement optimistic UI patterns
React Query does not support normalized caching. If your application requires normalized cache updates across multiple queries, consider using Apollo Client or Relay instead.

Setup with graphql-request

Install the required packages:
Create a GraphQL client:
lib/graphql-client.ts

Basic Query

Fetch data using GraphQL with React Query:

Query with Variables

Pass variables to your GraphQL queries:
Include variables in the query key to ensure React Query refetches when they change.

Mutations

Execute GraphQL mutations:

TypeScript + GraphQL Code Generator

For full type safety, use GraphQL Code Generator:
1

Install dependencies

2

Create codegen config

codegen.ts
3

Generate types

Add a script to package.json:
Run the generator:
4

Use generated types

The generated graphql() function provides full type inference for queries, mutations, and variables.

Pagination

Implement cursor-based pagination:

Optimistic Updates

Update the UI immediately for better UX:

Subscriptions

Handle GraphQL subscriptions:
Combine React Query’s caching with GraphQL subscriptions for real-time updates with offline support.

Error Handling

Handle GraphQL errors properly:

Query Key Factories

Organize GraphQL query keys:

Fragment Colocation

Colocate fragments with components:

Batching Requests

Batch multiple GraphQL requests:

Server-Side Rendering

Prefetch GraphQL queries for SSR:
See the Server-Side Rendering guide for detailed SSR integration instructions.

Complete Example

Next Steps

TypeScript

Learn about type-safe GraphQL queries

Server-Side Rendering

Implement SSR with GraphQL