Skip to main content

QueryClientProvider

The QueryClientProvider component provides the QueryClient instance to your React application. It must wrap any components that use TanStack Query hooks.

Import

Signature

Props

QueryClient
required
The QueryClient instance to provide to the application. Create this using new QueryClient().
React.ReactNode
The React components that will have access to the QueryClient.

Behavior

The QueryClientProvider component:
  1. Creates a React Context to provide the QueryClient
  2. Calls client.mount() when the component mounts
  3. Calls client.unmount() when the component unmounts
  4. Makes the QueryClient available to all child components via the useQueryClient hook

Examples

Basic Setup

With Custom Configuration

With React DevTools

Multiple Clients (Advanced)

With Persistence (Server-Side Rendering)

Accessing the Client in Components

useQueryClient

The useQueryClient hook allows you to access the QueryClient instance from any component within the provider:

Implementation Details

The implementation creates a React Context and manages the QueryClient lifecycle:

Common Patterns

Single Client Instance

Per-Request Client (SSR)

With Error Handling

Best Practices

  1. Create client outside component: Create the QueryClient instance outside your component or use useState to ensure it’s only created once
  2. Don’t create new clients on every render: This will cause all queries to reset
  3. Place high in component tree: Wrap your entire app or the highest level component that needs TanStack Query
  4. Use single client for most apps: Most applications only need one QueryClient instance
  5. SSR considerations: Create a new client per request in SSR environments to avoid sharing data between users
  6. DevTools in development: Include ReactQueryDevtools only in development builds

Type Definition

Source

Implementation: QueryClientProvider.tsx:29