TanStack Query v5: A Leap Forward in Simplicity and Functionality
Introduction:
Here at ThisDot we totally love TanStack Query, so we are really excited to share the news about the release of TanStack Query v5, the latest version of the powerful data-fetching library. The TanStack Query team has been hard at work, making significant improvements to enhance the library's usability and functionality. This blog post will explore the exciting new features and changes introduced in v5.
Breaking Changes:
One of the most notable changes in TanStack Query v5 is the removal of most overloads from the codebase. Previously, different overloads were used when calling useQuery
and other hooks, resulting in inconsistent usage patterns and subpar TypeScript error messages. With the introduction of TypeScript 4.7, the team was able to unify the usage of these hooks, resulting in a more consistent and streamlined API. Now, developers only need to pass a single object, making the API more intuitive and developer-friendly. To assist with the transition, the team has updated the documentation, released an auto-fixable eslint rule, and provided a codemod tool.
New Features:
TanStack Query v5 introduces a range of exciting new features that enhance the data-fetching experience. Let's explore some of them:
-
Simplified Optimistic Updates: Performing optimistic updates is now easier than ever with the
useMutation
hook. Developers can leverage the returned variables without manually updating the cache. This streamlined approach simplifies the process and improves efficiency. -
Sharable Mutation State: A highly requested feature, the
useMutationState
hook allows developers to access the state of all mutations across components. This shared state simplifies coordination and management of mutation-related data.
import { useMutation, useMutationState } from 'tanstack-query';
const mutationKey = ['example']
const mutation = useMutation({
mutationKey,
mutationFn: (...) => {
...
},
})
// In another component
const data = useMutatationState({
// this mutation key needs to match the one of the given mutation ('example' in our case)
filters: { mutationKey },
select: (mutation) => mutation.state.data,
})
-
1st Class Suspense Support: TanStack Query v5 fully supports suspense for data fetching. Hooks like
useSuspenseQuery
,useSuspenseInfiniteQuery
, anduseSuspenseQueries
enable seamless integration of suspense in applications, providing a more efficient and intuitive way to handle data fetching. -
Streaming with React Server Components: The new version introduces an experimental integration for suspense on the server in
Next.js
. By leveraging thereact-query-next-experimental
adapter, developers can initiate data fetching during server-side rendering (SSR) and stream the result to the client, combining interactivity and data synchronization. -
Improved Infinite Queries: Infinite Queries now supports prefetching multiple pages simultaneously, allowing developers to optimize performance. Additionally, the maximum number of pages stored in the cache can be specified, providing more control over memory usage.
// infinite query can be prefetched as a normal query
const prefetchExample = async () =>
await queryClient.prefetchInfiniteQuery({
queryKey: ['...key name...'],
queryFn: fetchFn,
initialPageParam: 0,
getNextPageParam: (lastPage, pages) => lastPage.nextCursor, // this is needed when you want to prefetch more than one page
pages: 5 // prefetch the first 5 pages
})
-
New Devtools: The Query devtools have been completely rewritten in a framework-agnostic manner, making them accessible to all adapters. With a revamped UI and new features like cache inline editing and light mode, developers can benefit from enhanced debugging capabilities.
-
Fine-Grained Persistence: Addressing a long-standing discussion, v5 introduces fine-grained persistence with the
experimental_createPersister
plugin. This plugin enables developers to persist queries individually, offering just-in-time restore capabilities, particularly beneficial for mobile development. -
The queryOptions API: With the unified
useQuery
API, v5 introduces thequeryOptions
function, enabling type-safe sharing of query definitions betweenuseQuery
and imperative methods likequeryClient.prefetchQuery
. This enhancement improves code maintainability and type safety.
import { queryOptions } from 'tanstack-query'
function groupOptions(){
return queryOptions({
queryKey: ['...key name...'],
queryFn: fetchFn,
staleTime: ...
})
}
useQuery(groupOptions())
queryClient.prefetchQuery(groupOptions())
Conclusion:
TanStack Query v5 marks a significant milestone in the evolution of the data-fetching library. The breaking changes and new features introduced in this version enhance the developer experience, simplify usage, and open up exciting possibilities for data management. We encourage fellow developers to explore the migration guide, check the docs and leverage the examples provided to make the most of TanStack Query v5. Upgrade today and experience the future of data fetching with TanStack Query!