Course contentsShow
← React
Lesson 1769 of 2,39642. Data Fetching LibrariesFree lesson

Installation and QueryClient Setup

Setting up TanStack Query with QueryClientProvider and basic configuration options.

Installation and QueryClient Setup

What you'll learn: How to install TanStack Query and configure the QueryClient to enable powerful server-state management in your React app.

Getting TanStack Query into Your Project

TanStack Query (formerly React Query) needs two things to work: the library itself and a central configuration hub called the QueryClient. Think of the QueryClient as the "control center" that manages all your data fetching operations—it holds cache settings, default behaviors, and coordinates all queries across your app.

Installation is straightforward via npm or yarn:

npm install @tanstack/react-query

Setting Up the QueryClient

The QueryClient is where you define how TanStack Query should behave globally. You create one instance and then wrap your app with QueryClientProvider to make it available everywhere:

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

// Create the client with default options
const queryClient = new QueryClient({
  defaultOptions: {
    queries: {
      staleTime: 60000, // Data stays "fresh" for 1 minute
      cacheTime: 300000, // Keep unused data cached for 5 minutes
      retry: 2, // Retry failed requests twice
    },
  },
});

function App() {
  return (
    <QueryClientProvider client={queryClient}>
      {/* Your app components */}
    </QueryClientProvider>
  );
}

The defaultOptions let you set baseline behaviors. For example, staleTime controls how long data is considered "fresh" before refetching, while cacheTime determines how long unused data stays in memory.

Key Takeaway: TanStack Query requires installing the package and wrapping your app in QueryClientProvider with a configured QueryClient—this single setup unlocks declarative data fetching throughout your entire application.