TanStack Query in React

TanStack Query in React TanStack Query (formerly React Query) is a popular library used in React applications to manage server state. It simplifies fetching, caching, updating, and synchronizing data from APIs. Normally, we use useState() and useEffect() to handle API requests. TanStack Query provides built-in features to manage these operations with less code. 1. Installation and Setup Install TanStack Query using npm: npm install @tanstack/react-query Wrap your application with QueryClientProvider in main.jsx. import { QueryClient, QueryClientProvider } from "@tanstack/react-query"; const queryClient = new QueryClient(); createRoot(document.getElementById("root")).render( ); This makes TanStack Query available throughout the application. 2. useQuery() useQuery() is used to fetch data from an API using GET requests. import { useQuery } from "@tanstack/react-query"; import axios from "axios"; const { data, isPending

TanStack Query in React

TanStack Query in React

TanStack Query (formerly React Query) is a popular library used in React applications to manage server state. It simplifies fetching, caching, updating, and synchronizing data from APIs.

Normally, we use useState() and useEffect() to handle API requests. TanStack Query provides built-in features to manage these operations with less code.

1. Installation and Setup

Install TanStack Query using npm:

npm install @tanstack/react-query

Wrap your application with QueryClientProvider in main.jsx.

import { QueryClient, QueryClientProvider } from "@tanstack/react-query";

const queryClient = new QueryClient();

createRoot(document.getElementById("root")).render(
  <QueryClientProvider client={queryClient}>
    <App />
  QueryClientProvider>
);

This makes TanStack Query available throughout the application.

2. useQuery()

useQuery() is used to fetch data from an API using GET requests.

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

const { data, isPending, isError } = useQuery({
  queryKey: ["users"],

  queryFn: async () => {
    const response = await axios.get(
      "https://dummyjson.com/users"
    );

    return response.data.users;
  }
});

Important properties:

  • queryKey: Uniquely identifies a query and its cached data.
  • queryFn: Function responsible for fetching data.
  • data: Contains the API response.
  • isPending: Indicates that the query has no data yet and is pending.
  • isError: Indicates that the query failed.

3. useMutation()

useMutation() is used to create, update, and delete data using POST, PUT, PATCH and DELETE requests.

Example: Adding a new user.

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

const addUser = useMutation({
  mutationFn: async (newUser) => {
    const response = await axios.post(
      "https://dummyjson.com/users/add",
      newUser
    );

    return response.data;
  }
});

// Execute mutation
addUser.mutate({
  firstName: "John",
  age: 25
});

Important properties:

  • mutationFn: Contains the API request.
  • mutate(): Executes the mutation.
  • isPending: Indicates that the mutation is running.
  • isSuccess: Indicates successful execution.
  • isError: Indicates that the mutation failed.

4. useQueryClient()

useQueryClient() provides access to the Query Client. It helps manage cached API data.

One important use is refreshing cached data after a successful mutation.

import { useQueryClient, useMutation } from "@tanstack/react-query";

const queryClient = useQueryClient();

const addUser = useMutation({
  mutationFn: addUserAPI,

  onSuccess: () => {
    queryClient.invalidateQueries({
      queryKey: ["users"]
    });
  }
});

Here, invalidateQueries() marks the existing users query as stale(or old). If the query is active, TanStack Query normally refetches it automatically.

Share