How to Use TanStack Query in React: Simple Guide
To use
TanStack Query in React, first install the package and wrap your app with QueryClientProvider. Then use the useQuery hook inside components to fetch and cache data easily with automatic updates.Syntax
The main parts of using TanStack Query in React are:
QueryClient: Manages cache and settings.QueryClientProvider: Wraps your app to provide query context.useQuery: Hook to fetch data and track loading/error states.
Each useQuery call needs a unique key and a function that returns a promise with the data.
jsx
import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <MyComponent /> </QueryClientProvider> ); } function MyComponent() { const { data, error, isLoading } = useQuery(['key'], fetchDataFunction); if (isLoading) return 'Loading...'; if (error) return 'Error!'; return <div>{JSON.stringify(data)}</div>; }
Example
This example shows how to fetch a list of users from a public API using useQuery. It handles loading and error states and displays the user names.
jsx
import React from 'react'; import { QueryClient, QueryClientProvider, useQuery } from '@tanstack/react-query'; const queryClient = new QueryClient(); async function fetchUsers() { const response = await fetch('https://jsonplaceholder.typicode.com/users'); if (!response.ok) throw new Error('Network response was not ok'); return response.json(); } function Users() { const { data, error, isLoading } = useQuery(['users'], fetchUsers); if (isLoading) return <p>Loading users...</p>; if (error) return <p>Error loading users</p>; return ( <ul> {data.map(user => ( <li key={user.id}>{user.name}</li> ))} </ul> ); } export default function App() { return ( <QueryClientProvider client={queryClient}> <Users /> </QueryClientProvider> ); }
Output
<ul><li>Leanne Graham</li><li>Ervin Howell</li><li>Clementine Bauch</li><li>Patricia Lebsack</li><li>Chelsey Dietrich</li><li>Mrs. Dennis Schulist</li><li>Kurtis Weissnat</li><li>Nicholas Runolfsdottir V</li><li>Glenna Reichert</li><li>Clementina DuBuque</li></ul>
Common Pitfalls
Common mistakes when using TanStack Query include:
- Not wrapping your app with
QueryClientProvider, which causes hooks to fail. - Using non-unique or changing keys in
useQuery, which breaks caching. - Not handling loading and error states, leading to confusing UI.
- Fetching data outside
useQuery, losing benefits like caching and automatic refetch.
jsx
/* Wrong: Missing QueryClientProvider */ function App() { return <Users />; // useQuery will error } /* Right: Wrap with QueryClientProvider */ import { QueryClient, QueryClientProvider } from '@tanstack/react-query'; const queryClient = new QueryClient(); function App() { return ( <QueryClientProvider client={queryClient}> <Users /> </QueryClientProvider> ); }
Quick Reference
Here is a quick cheat sheet for TanStack Query in React:
| Concept | Description |
|---|---|
| QueryClient | Manages cache and query settings |
| QueryClientProvider | Wraps app to provide query context |
| useQuery(key, fetchFn) | Fetches data and tracks loading/error |
| queryKey | Unique key to identify cached data |
| isLoading | True while data is loading |
| error | Error object if fetch fails |
| data | Fetched data when successful |
Key Takeaways
Always wrap your React app with QueryClientProvider before using useQuery.
Use unique and stable keys in useQuery to enable caching and updates.
Handle loading and error states to improve user experience.
Define your data fetching function as an async function returning a promise.
TanStack Query automatically caches and updates data for you.