TanStack Query With Its Key Hooks and Examples

TanStack Query With Its Key Hooks and Examples

TanStack Query in a Nutshell:

  • A powerful data fetching and caching library for React, Vue, Solid, Svelte, and vanilla JS.
  • Simplifies asynchronous data management and reduces boilerplate code.
  • Offers optimistic updates, automatic refetching, and offline support.
  • Integrates seamlessly with React Query Devtools for debugging and inspection.

Key Hooks:

1. useQuery:

  • Fetches data from an asynchronous source (API, database, etc.).
  • Automatically caches and refetches data based on configuration.
  • Manages loading, error, and success states.



import { useQuery } from '@tanstack/react-query';

function Posts() {
  const { isLoading, error, data } = useQuery('posts', fetchPosts);

  if (isLoading) return <div>Loading posts...</div>;
  if (error) return <div>Error fetching posts: {error.message}</div>;

  return (
      {data.map((post) => (
        <li key={post.id}>{post.title}</li>

2. useInfiniteQuery:

  • Fetches data in infinite scrolling or pagination scenarios.
  • Fetches additional data as the user scrolls or navigates.



import { useInfiniteQuery } from '@tanstack/react-query';

function InfinitePosts() {
  const { fetchNextPage, hasNextPage, isLoading, error, data } = useInfiniteQuery(
    { getNextPageParam: (lastPage) => lastPage.nextPage }

  // ... handle loading, error, and render posts

3. useMutation:

  • Executes mutations (create, update, delete) on remote data.
  • Manages optimistic updates and potentially refetches related queries.



import { useMutation } from '@tanstack/react-query';

function CreatePost() {
  const createPostMutation = useMutation(createPost);

  // ... handle form submission and mutation execution

Additional Hooks:

  • useQueryClient: Access the query client for advanced control and custom hooks.
  • useIsFetching: Check if a query is currently fetching data.
  • useQueries: Fetch multiple queries in parallel.

Key Features:

  • Optimistic Updates: Updates the UI immediately, even before server responses.
  • Automatic Refetching: Refetches queries based on configuration (e.g., on focus, window focus, interval).
  • Offline Support: Caches data for offline availability.
  • React Query Devtools: Powerful debugging and inspection tool.

Official Resources:

Leave a Reply

Your email address will not be published. Required fields are marked *