React Query (TanStack Query) — Complete Guide
Advertisement
React Query (TanStack Query) — Complete Guide
React Query (now TanStack Query) handles server state management with caching, synchronization, and background updates.
- React Query (TanStack Query) — Complete Guide
- Installation
- Provider Setup
- useQuery
- useMutation
- Caching
- Real-World Example
- FAQ
Installation
npm install @tanstack/react-query
Provider Setup
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
const queryClient = new QueryClient()
export default function App() {
return (
<QueryClientProvider client={queryClient}>
<YourApp />
</QueryClientProvider>
)
}
useQuery
Fetch data:
const { data, isLoading, error } = useQuery({
queryKey: ['posts'],
queryFn: () => fetch('/api/posts').then(r => r.json())
})
useMutation
Handle mutations:
const createPostMutation = useMutation({
mutationFn: (post) =>
fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(post)
}).then(r => r.json()),
onSuccess: () => {
queryClient.invalidateQueries(['posts'])
}
})
function handleSubmit(post) {
createPostMutation.mutate(post)
}
Caching
Query results auto-cache:
const query = useQuery({
queryKey: ['user', userId],
queryFn: () => fetch(`/api/users/${userId}`).then(r => r.json()),
staleTime: 60000, // 1 minute
gcTime: 5 * 60 * 1000 // 5 minutes (formerly cacheTime)
})
Real-World Example
function PostList() {
const { data: posts, isLoading } = useQuery({
queryKey: ['posts'],
queryFn: async () => {
const res = await fetch('/api/posts')
return res.json()
}
})
const createMutation = useMutation({
mutationFn: async (newPost) => {
const res = await fetch('/api/posts', {
method: 'POST',
body: JSON.stringify(newPost)
})
return res.json()
},
onSuccess: () => {
queryClient.invalidateQueries(['posts'])
}
})
if (isLoading) return <div>Loading...</div>
return (
<div>
{posts?.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
)
}
FAQ
Q: How does React Query differ from useEffect? A: React Query handles caching, background sync, and refetching automatically.
Q: Should I use React Query with Next.js? A: Use Next.js Server Components for initial data, React Query for client-side updates.
Q: What's gcTime vs staleTime? A: staleTime = how long before refetch. gcTime = how long to keep cached.
React Query simplifies complex server state management patterns.
Advertisement