Skip to content

Instantly share code, notes, and snippets.

@Krishprajapati15
Created June 24, 2025 10:58
Show Gist options
  • Select an option

  • Save Krishprajapati15/4497b48a61072f9be29116ab38216ed7 to your computer and use it in GitHub Desktop.

Select an option

Save Krishprajapati15/4497b48a61072f9be29116ab38216ed7 to your computer and use it in GitHub Desktop.
TanStack Query (formerly React Query) is a powerful, framework-agnostic data-fetching and caching library for building fast, reactive, and resilient web applications. It manages server state, caching, background sync, pagination, and much more—so you can focus on building features, not fetching data.

TanStack Query: Powerful Data Fetching for Modern Apps

TanStack Query (formerly React Query) is a powerful, framework-agnostic data-fetching and caching library for building fast, reactive, and resilient web applications. It manages server state, caching, background sync, pagination, and much more—so you can focus on building features, not fetching data.


🚀 Key Features

  • Smart Caching – Automatic and configurable caching of server data, minimizing unnecessary requests.
  • Background Synchronization – Keep data fresh by refetching in the background, on focus, or reconnect.
  • Mutation Management – Powerful tools for handling create, update, and delete operations with optimistic updates and rollback.
  • Pagination & Infinite Queries – Effortlessly manage paginated or infinite scrolling data.
  • Devtools – Inspect and debug your queries and mutations in real time.
  • Framework Agnostic – Works with React, Solid, Svelte, Vue, and more.
  • First-Class Typescript Support – Full type safety for queries and mutations.

🛠️ How to Use TanStack Query

  1. Install the Package

    • For React:
      npm install @tanstack/react-query
  2. Set Up the Query Client

    • Wrap your app with the QueryClientProvider and create a QueryClient instance.
      import { QueryClient, QueryClientProvider } from '@tanstack/react-query';
      
      const queryClient = new QueryClient();
      
      function App() {
        return (
          <QueryClientProvider client={queryClient}>
            {/* Your app */}
          </QueryClientProvider>
        );
      }
  3. Basic Data Fetching Example

    • Use the useQuery hook to fetch and cache data.
      import { useQuery } from '@tanstack/react-query';
      
      function Todos() {
        const { data, isLoading, error } = useQuery({
          queryKey: ['todos'],
          queryFn: () => fetch('/api/todos').then(res => res.json())
        });
      
        if (isLoading) return <span>Loading...</span>;
        if (error) return <span>Error: {error.message}</span>;
      
        return (
          <ul>
            {data.map(todo => <li key={todo.id}>{todo.title}</li>)}
          </ul>
        );
      }
  4. Mutations Example

    • Use the useMutation hook for creating/updating/deleting data.
      import { useMutation, useQueryClient } from '@tanstack/react-query';
      
      function AddTodo() {
        const queryClient = useQueryClient();
      
        const mutation = useMutation({
          mutationFn: newTodo =>
            fetch('/api/todos', {
              method: 'POST',
              body: JSON.stringify(newTodo),
              headers: { 'Content-Type': 'application/json' }
            }),
          onSuccess: () => {
            queryClient.invalidateQueries(['todos']);
          }
        });
      
        // ...form logic to call mutation.mutate(newTodo)
      }
  5. Devtools

    • Install and use the devtools for debugging:
      npm install @tanstack/react-query-devtools
      import { ReactQueryDevtools } from '@tanstack/react-query-devtools';
      
      <QueryClientProvider client={queryClient}>
        {/* Your app */}
        <ReactQueryDevtools initialIsOpen={false} />
      </QueryClientProvider>

💡 When to Use TanStack Query

  • Fetching and caching remote data in any modern frontend framework.
  • Synchronizing server and client state (e.g., after mutations).
  • Background data refresh for real-time or near-real-time UIs.
  • Managing paginated or infinite-scroll data.
  • Optimistically updating UI for a responsive user experience.
  • Complex apps with lots of remote data dependencies.

🖥️ Example: Simple Data Fetch with useQuery

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

function Example() {
  const { data, isLoading } = useQuery({
    queryKey: ['example'],
    queryFn: () => fetch('/api/example').then(res => res.json()),
  });

  if (isLoading) return 'Loading...';
  return <pre>{JSON.stringify(data, null, 2)}</pre>;
}

📚 Resources


Learn more at tanstack.com/query

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment