Skip to content

TanStack Query

Anastasia Mexa edited this page Mar 11, 2024 · 2 revisions

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:

Installation

First, you need to install TanStack Query and its dependencies. You can do this via the npm command:

npm install @tanstack/react-query

Setting up a 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 the fetchPosts 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, and isError variables. We use these variables to handle loading and error states.

Caching and Invalidation

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.

Pagination and Infinite Loading

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.

Clone this wiki locally