Skip to main content

Quick Start

This guide will help you build your first React application with TanStack Query.

Prerequisites

Make sure you have React Query installed. If not, follow the installation guide.

Basic Example

1

Set up the QueryClient

First, create a QueryClient and wrap your app with QueryClientProvider:
src/main.tsx
2

Create your first query

Use the useQuery hook to fetch data:
src/App.tsx
3

Run your application

Start your development server and you should see the posts loading and displaying!
Notice how React Query automatically handles loading states, error states, and caching for you.

Understanding Query Keys

Query keys uniquely identify queries. They can be simple strings or arrays:
Use array keys when your query depends on parameters. React Query will automatically refetch when these parameters change.

Adding Mutations

Mutations are used to create, update, or delete data:

Query with Parameters

Fetch data based on dynamic parameters:
React Query will automatically refetch when postId changes because it’s part of the query key.

Complete Example

Here’s a complete CRUD example:
src/App.tsx

Error Handling

Handle errors gracefully:
Always throw errors in your queryFn for React Query to handle them properly. Don’t catch errors unless you want to transform them.

Loading States

Provide better UX with detailed loading states:
Use isLoading for initial load and isFetching to show background refresh indicators.

Optimistic Updates

Update the UI immediately for better perceived performance:

Query Options

Use queryOptions for reusable, type-safe query configurations:

Next Steps

TypeScript

Add type safety to your queries and mutations

DevTools

Debug your queries with React Query DevTools

Server-Side Rendering

Learn about SSR with Next.js and other frameworks

GraphQL

Use React Query with GraphQL