Data Fetching with TanStack React Query
Powerful data fetching, caching, and synchronization for modern apps
Provides powerful data fetching, caching, and synchronization for APIs, ideal for e-commerce (product lists) and social media (infinite feeds). Simplifies async operations with hooks, reducing boilerplate compared to axios alone.
Works seamlessly with Hono.js APIs and supports optimistic updates for real-time features. Chosen for its performance and developer experience, enhancing your full-stack workflow with features like automatic background refetching and intelligent caching.
- Intelligent Caching
Automatic caching with smart invalidation
- Background Updates
Automatic background refetching
- Request Deduplication
Eliminates duplicate requests automatically
- Optimistic Updates
Real-time UI updates before server response
- Infinite Queries
Perfect for pagination and infinite scrolling
- Offline Support
Works seamlessly offline with cached data
- • Product catalogs
- • Order history
- • Search results
- • Inventory updates
- • Infinite feeds
- • User profiles
- • Comments and likes
- • Notifications
- • Live updates
- • Chat messages
- • Activity feeds
- • Status changes
Installation
npm install @tanstack/react-query
Basic Query Example
import { useQuery } from '@tanstack/react-query'
function ProductList() {
const { data, isLoading, error } = useQuery({
queryKey: ['products'],
queryFn: () => fetch('/api/products').then(res => res.json())
})
if (isLoading) return <Text>Loading...</Text>
if (error) return <Text>Error loading products</Text>
return (
<FlatList
data={data}
renderItem={({ item }) => <ProductCard product={item} />}
/>
)
}
Infinite Query for Feeds
import { useInfiniteQuery } from '@tanstack/react-query'
function SocialFeed() {
const {
data,
fetchNextPage,
hasNextPage,
isFetchingNextPage,
} = useInfiniteQuery({
queryKey: ['posts'],
queryFn: ({ pageParam = 0 }) =>
fetch(`/api/posts?page=${pageParam}`).then(res => res.json()),
getNextPageParam: (lastPage, pages) => lastPage.nextPage,
})
return (
<FlatList
data={data?.pages.flatMap(page => page.posts)}
onEndReached={() => hasNextPage && fetchNextPage()}
renderItem={({ item }) => <PostCard post={item} />}
/>
)
}