QueryClient, QueryClientProvider, and useQuery
Set up TanStack Query with a QueryClient, wrap the app in QueryClientProvider, and fetch data with useQuery — replacing manual useEffect-based fetching.
What Is TanStack React Query?
TanStack React Query (formerly React Query) is a data-fetching and caching library that manages server state in your React Native app. Instead of managing loading, error, and data state manually with useState and useEffect, React Query provides smart caching, background refetching, and automatic retry — all with a simple hook API.
Server state is inherently different from UI state: it lives on a remote server, can be stale, needs refetching, and multiple components might need the same data. React Query solves all of this in a battle-tested, production-proven way.
// Traditional approach (before React Query):
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
// With React Query:
const { data, isLoading, error } = useQuery({
queryKey: ['posts'],
queryFn: fetchPosts,
});
// Same result — dramatically less codeInstalling TanStack Query
Install TanStack Query (v5) and the React Native specific persistence plugin. The core package is @tanstack/react-query. For Expo projects you may also want the devtools, though they require a web environment to view.
React Query v5 uses object syntax for hook options (breaking change from v4). If you see tutorials using positional arguments for useQuery, they are using v4. This lesson covers the modern v5 API.
// Install:
// npx expo install @tanstack/react-query
// npx expo install @tanstack/react-query-persist-client
// npx expo install @tanstack/async-storage-persister
// npx expo install @react-native-async-storage/async-storage
import { QueryClient, QueryClientProvider } from '@tanstack/react-query';All lessons in this course
- QueryClient, QueryClientProvider, and useQuery
- Mutations with useMutation and Cache Invalidation
- Persisting the Query Cache with AsyncStorage
- Background Refetch and Stale Time Configuration