DEV Community

Cover image for TanStack Query in React
Mahalakshmi C
Mahalakshmi C

Posted on

TanStack Query in React

1. What is TanStack Query?

TanStack Query is a library used to fetch, cache, update, and manage server data in React applications.

It was previously known as React Query.

When we fetch data from an API using Axios or fetch(), we usually need to manage loading, error, and data states ourselves. TanStack Query helps manage these tasks and provides features such as caching and automatic refetching.

2. Why do we use TanStack Query?

  • Fetching data: Gets data from an API.
  • Caching: Stores previously fetched data to reduce unnecessary requests.
  • Loading state: Helps us know when data is loading.
  • Error handling: Makes it easier to handle API errors.
  • Automatic refetching: Can fetch updated data when certain events occur.
  • Mutations: Helps create, update, and delete server data.

3. How to install TanStack Query

Install the package:

npm install @tanstack/react-query 
Enter fullscreen mode Exit fullscreen mode

4. Setting up TanStack Query

First, create a QueryClient and wrap the application with QueryClientProvider.

main.jsx

import React from "react";
import ReactDOM from "react-dom/client";
import { QueryClient, QueryClientProvider } from "@tanstack/react-query";
import App from "./App";

const queryClient = new QueryClient();

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

Explanation:

  • QueryClient manages caching and query-related operations.
  • QueryClientProvider makes the query client available to components inside it.

5. What is useQuery()?

useQuery() is a hook used to fetch and manage data from a server.

Example using Axios

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

function App() {
  const { data, isLoading, isError } = useQuery({
    queryKey: ["users"],
    queryFn: async () => {
      const response = await axios.get(
        "https://jsonplaceholder.typicode.com/users"
      );
      return response.data;
    },
  });

  if (isLoading) return <p>Loading...</p>;
  if (isError) return <p>Something went wrong!</p>;

  return (
    <div>
      <h2>User List</h2>
      {data.map((user) => (
        <p key={user.id}>{user.name}</p>
      ))}
    </div>
  );
}

export default App;
Enter fullscreen mode Exit fullscreen mode

Important properties

  • queryKey: A unique key that identifies the query and its cached data.
  • queryFn: The function that fetches the data.
  • data: The successfully returned data.
  • isLoading: Indicates that the query has no data yet and is loading.
  • isError: Indicates that the query failed.

6. What is useMutation()?

useMutation() is used to create, update, or delete data on the server.

For example, adding a new user:

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

function AddUser() {
  const mutation = useMutation({
    mutationFn: (newUser) =>
      axios.post(
        "https://jsonplaceholder.typicode.com/users",
        newUser
      ),
  });

  const handleAdd = () => {
    mutation.mutate({
      name: "Maha",
      email: "maha@example.com",
    });
  };

  return (
    <div>
      <button onClick={handleAdd}>Add User</button>
      {mutation.isPending && <p>Adding user...</p>}
      {mutation.isError && <p>Failed to add user.</p>}
      {mutation.isSuccess && <p>User added successfully!</p>}
    </div>
  );
}

export default AddUser;
Enter fullscreen mode Exit fullscreen mode

This example sends a POST request. The JSONPlaceholder API is a testing API, so the created user is not permanently saved.

7. What is caching?

Caching means keeping previously fetched data so it can be reused instead of requesting the same data unnecessarily.

For example, when a user list is fetched once, TanStack Query can keep that data in its cache. When the same query is used again, the cached data may be available immediately while a background refetch happens when appropriate.

The queryKey helps TanStack Query identify which cached data belongs to which query.

8. TanStack Query vs useEffect() and Axios

Feature useEffect() + Axios TanStack Query
Fetch API data Yes Yes
Loading and error state Manage manually Built-in query states
Caching Build it yourself Built-in
Refetching Implement manually Built-in options
Server-data updates Manage manually Supports mutations and cache updates

Axios and TanStack Query are not replacements for each other. Axios makes the request; TanStack Query manages the request's server-state lifecycle.

9. How does TanStack Query work?

  1. A component calls useQuery().
  2. TanStack Query checks the query key and cache.
  3. If needed, it runs the queryFn to fetch data.
  4. The component receives loading, error, and data states.
  5. The result is cached and can be reused by matching queries.

Top comments (0)