0Pricing
React Academy · Lesson

Setting Up React Query & QueryClient

Install TanStack Query, wrap your app in QueryClientProvider, and run your first useQuery.

Setting Up React Query & QueryClient is a free React Academy lesson on CoddyKit — lesson 1 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the React Academy learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.

Welcome

In this lesson you will install TanStack Query, set up QueryClient and QueryClientProvider, and run your first useQuery to fetch data from an API.

What Is React Query?

TanStack Query (formerly React Query) manages server state: fetching, caching, synchronising, and updating data from remote sources. It replaces manual loading/error state and useEffect-based data fetching.

Installation

Install the core package and optionally the DevTools.
npm install @tanstack/react-query
npm install @tanstack/react-query-devtools --save-dev

Creating a QueryClient

Create a QueryClient instance to hold all caching and configuration. Pass it to QueryClientProvider which wraps your app.
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';

const queryClient = new QueryClient();

createRoot(document.getElementById('root')).render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>
);

Your First useQuery

Call useQuery with a queryKey array and a queryFn that returns the data. The key uniquely identifies the cached entry.
import { useQuery } from '@tanstack/react-query';

function Posts() {
  const { data, isLoading, isError } = useQuery({
    queryKey: ['posts'],
    queryFn: () => fetch('/api/posts').then(r => r.json()),
  });

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Error!</p>;
  return <ul>{data.map(p => <li key={p.id}>{p.title}</li>)}</ul>;
}

Query Keys

Query keys are arrays. Add parameters to the key to scope the cache entry. Different keys = different cache entries.
// All posts
useQuery({ queryKey: ['posts'], queryFn: fetchPosts })

// Post with id 5
useQuery({ queryKey: ['posts', 5], queryFn: () => fetchPost(5) })

// Posts filtered by category
useQuery({ queryKey: ['posts', { category: 'react' }], queryFn: /* ... */ })

Query Status

useQuery returns multiple status properties: `isLoading`, `isFetching`, `isError`, `isSuccess`, `data`, and `error`. `isFetching` is true even for background refetches; `isLoading` is true only on the first load.

React Query DevTools

Add ReactQueryDevtools to your app in development to see all cache entries, their status, and when they were last fetched. This is invaluable for debugging.
import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

<QueryClientProvider client={queryClient}>
  <App />
  <ReactQueryDevtools initialIsOpen={false} />
</QueryClientProvider>

Default Configuration

Configure global defaults on the QueryClient: staleTime, gcTime (garbage collection), retry count, and refetchOnWindowFocus.
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60_000,     // data is fresh for 60s
      retry: 2,              // retry failed queries twice
      refetchOnWindowFocus: false,
    },
  },
});

Automatic Refetching

By default, React Query refetches stale data when: the window regains focus, the component remounts, and the network reconnects. These can be configured individually on each query.

Quick Check

What is the purpose of the queryKey array in useQuery?

Recap

Install @tanstack/react-query, create QueryClient, wrap your app with QueryClientProvider, and call useQuery with a queryKey and queryFn. Add DevTools for visibility. Configure global defaults on QueryClient.

Up Next

Next lesson: **Caching, Stale Time & Background Refetching** — you will configure staleTime and gcTime to control when data is re-fetched.

Frequently asked questions

Is the “Setting Up React Query & QueryClient” lesson free?

Yes — the full text of “Setting Up React Query & QueryClient” is free to read here on the web, and the React Academy course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the React Academy course, upgrade to CoddyKit PRO.

What will I learn in “Setting Up React Query & QueryClient”?

Install TanStack Query, wrap your app in QueryClientProvider, and run your first useQuery. You practise React Academy with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.

Do I need any experience to start React Academy?

No prior experience is required. React Academy on CoddyKit is structured for beginners through advanced learners; this is — lesson 1 of 4, so you can start here or from the beginning and move at your own pace.

How long does the “Setting Up React Query & QueryClient” lesson take?

Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.

Can I write and run code in this React Academy lesson?

Yes. Every React Academy lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.

All lessons in this course

  1. Setting Up React Query & QueryClient
  2. Caching, Stale Time & Background Refetching
  3. Mutations with useMutation
  4. Infinite Scroll & Pagination with useInfiniteQuery
← Back to React Academy