-
Notifications
You must be signed in to change notification settings - Fork 0
TanStack Query
TanStack Query is a data fetching and caching library for React. TanStack Query builds upon the principles of React Query but provides a more flexible and extensible approach to data fetching and caching.
Here are some basics about TanStack Query along with examples:
First, you need to install TanStack Query and its dependencies. You can do this via the npm command:
npm install @tanstack/react-query
You can create a query using the useQuery hook provided by TanStack Query. Here's a basic example:
import { useQuery } from '@tanstack/react-query';
const fetchPosts = async () => {
const response = await fetch('https://api.example.com/posts');
return response.json();
};
const MyComponent = () => {
const { data, isLoading, isError } = useQuery('posts', fetchPosts);
if (isLoading) return <div>Loading...</div>;
if (isError) return <div>Error fetching data</div>;
return (
<div>
{data.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
);
};
In this example:
- We define a function
fetchPosts
that fetches data from an API endpoint. - We use the
useQuery
hook to fetch data using thefetchPosts
function. The first argument is the key for the query, and the second argument is the function that performs the data fetching. - The hook returns
data
,isLoading
, andisError
variables. We use these variables to handle loading and error states.
TanStack Query automatically caches query results, which means subsequent requests for the same data will be served from the cache. You can also manually invalidate or refetch queries using the invalidateQueries
and refetchQueries
functions.
import { useQueryClient } from '@tanstack/react-query';
const MyComponent = () => {
const queryClient = useQueryClient();
const handleRefresh = () => {
queryClient.invalidateQueries('posts');
};
return (
<div>
<button onClick={handleRefresh}>Refresh</button>
{/* Display posts */}
</div>
);
};
In this example, clicking the "Refresh" button invalidates the 'posts' query, forcing it to refetch data from the server.
TanStack Query provides built-in support for pagination and infinite loading using the useInfiniteQuery
hook. This allows you to fetch paginated data and load more data as the user scrolls.
import { useInfiniteQuery } from '@tanstack/react-query';
const fetchPosts = async ({ pageParam = 1 }) => {
const response = await fetch(`https://api.example.com/posts?page=${pageParam}`);
return response.json();
};
const MyComponent = () => {
const { data, fetchNextPage, hasNextPage, isFetchingNextPage } = useInfiniteQuery('posts', fetchPosts, {
getNextPageParam: (lastPage, allPages) => lastPage.nextPage,
});
return (
<div>
{data.pages.map(page => (
<div key={page.pageId}>
{page.data.map(post => (
<div key={post.id}>{post.title}</div>
))}
</div>
))}
{hasNextPage && (
<button onClick={() => fetchNextPage()} disabled={isFetchingNextPage}>
{isFetchingNextPage ? 'Loading more...' : 'Load More'}
</button>
)}
</div>
);
};
In this example, we use useInfiniteQuery
to fetch paginated data. We also use the fetchNextPage
function to load more data when the user clicks the "Load More" button.
These are just some basic examples of how to use TanStack Query in a React application. It offers many more features like mutation handling, optimistic updates, and query invalidation, making it a powerful tool for managing data in React applications.
- Home
- Creating a React project
- Compilation and execution process
- Components & File Extensions
- React Basics
- Examples (Components and States)
- Using Fragments
- Setting Default Prop Values
- Fowarding Props
- Working with Multiple JSX Slots
- Setting Component Types Dynamically
- Updating state based on previous state value
- JavaScript Data Types and Memory Storage
- StrictMode Component
- Using Ref
- Forwarding Refs
- Context-API
- useReducer
- Side Effects
- Memoization
- Functional vs Class‐Based Components
- Performing HTTP requests
- Custom Hooks
- Form Submission and Validation
- Redux
- Router
- Lazy-Loading
- TanStack Query
- Next.js
- TypeSript