What is @tanstack/query-core?
The @tanstack/query-core package is a lightweight and powerful data synchronization library for JavaScript. It enables efficient server state management by providing hooks and utilities to fetch, cache, and update data in React applications. The core package is framework-agnostic and can be used with any JavaScript framework or UI layer.
What are @tanstack/query-core's main functionalities?
Data Fetching
This feature allows you to fetch data from an API or any asynchronous source. The useQuery hook returns the data, error, and loading state, making it easy to build UI components that react to data fetching state.
import { QueryClient, QueryCache, useQuery } from '@tanstack/query-core';
const queryClient = new QueryClient({
queryCache: new QueryCache(),
});
const { data, error, isLoading } = useQuery(['todos'], fetchTodos);
Data Caching
Data caching enables efficient data retrieval by storing fetched data in a cache. This reduces the need for unnecessary network requests, as subsequent requests for the same data can be served from the cache.
import { QueryClient, QueryCache } from '@tanstack/query-core';
const queryClient = new QueryClient({
queryCache: new QueryCache(),
});
queryClient.setQueryData(['todos'], updatedTodos);
Data Mutation
Data mutation is the process of updating data on the server and then synchronizing the updated data with the client. The useMutation hook is used to perform mutations, and it provides callbacks such as onSuccess to handle side effects like invalidating the cache to refetch updated data.
import { QueryClient, QueryCache, useMutation } from '@tanstack/query-core';
const queryClient = new QueryClient({
queryCache: new QueryCache(),
});
const mutation = useMutation(addTodo, {
onSuccess: () => {
queryClient.invalidateQueries(['todos']);
},
});
Other packages similar to @tanstack/query-core
react-query
React Query is a powerful data fetching and caching library for React. It is built on top of @tanstack/query-core and provides React-specific hooks for data fetching, caching, and updating. It offers similar functionalities but is tailored specifically for React applications.
swr
SWR is a React hooks library for data fetching. It stands for 'stale-while-revalidate' and focuses on providing a fast user experience by returning cached data first and then revalidating it in the background. It is similar to @tanstack/query-core in terms of caching and updating data, but it has a different API and revalidation strategy.
apollo-client
Apollo Client is a comprehensive state management library for JavaScript that enables you to manage both local and remote data with GraphQL. It is more specialized than @tanstack/query-core as it is designed to work with GraphQL APIs and provides advanced features like optimistic UI updates and fine-grained control over the cache.