DEV Community

Cover image for TANStack Query: How It Changes the Way You Query APIs
code-with-onye
code-with-onye

Posted on

TANStack Query: How It Changes the Way You Query APIs

In today's world of web development, querying APIs has become a common task for developers. However, the process of making HTTP requests, handling responses, and dealing with data formatting can be cumbersome and error-prone. This is where TANStack Query comes into play.

TANStack Query is a lightweight JavaScript library that provides developers with a simple and intuitive API for querying APIs. It is based on the Fetch API and allows developers to write concise and declarative code for making HTTP requests and handling responses. This article will discuss how TANStack Query works, the way it changes the API querying process, and the benefits it offers.

How TANStack query works:

TANStack Query works by first checking the query cache [2] to determine if the data has already been fetched. If the data is not in the cache, or if the cached data is stale, TANStack Query sends an HTTP request to the API endpoint [3] to retrieve the data, which is then stored in the cache [2]. Finally, TANStack Query returns the data from the cache to the user [5].

Flow of how tanstack query works

Compared to traditional HTTP fetching, TANStack Query offers several advantages. It reduces the need for component-level state management and code repetition. By abstracting away the complexity of HTTP requests and response handling, TANStack Query simplifies the process of querying APIs and managing data in React applications. Additionally, by caching the query results, TANStack Query reduces network traffic and improves application performance.

To start using TANStack Query in your project, you need to initialize it. This involves setting up the query in your app.jsx file. Here are the steps you can follow:

  • Import the necessary components from the TANStack Query library using the following code:
import {
    QueryClient,
    QueryClientProvider,
    useQuery,
  } from '@tanstack/react-query'
Enter fullscreen mode Exit fullscreen mode

Create a new instance of the QueryClient object, which will be used to manage the query cache:

const queryClient = new QueryClient()
Enter fullscreen mode Exit fullscreen mode

Wrap your application component in a QueryClientProvider component, which provides the QueryClient instance to all child components:

export default function App() {
    return (
      <QueryClientProvider client={queryClient}>
        <Example />
      </QueryClientProvider>
    )
  }
Enter fullscreen mode Exit fullscreen mode
  • You can now use the useQuery hook to make HTTP requests and handle responses.

For example, let's say we want to fetch a list of users from an API. Here's how we can use the useQueryhook :

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

export default function Users() {
  const { data, error, isLoading } = useQuery({
    queryKey: ["users"],
    queryFn: async () => await axios.get("https://dummyjson.com/users"),
  });

  console.log(data.data.users);

  if (isLoading) {
    return <div>Loading...</div>;
  }

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

  return (
    <ul>
      {data.data.users.map((user) => (
        <li key={user.id} style={{ color: "black" }}>
          {user.firstName}
        </li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

This code defines a request to fetch data from the [https://dummyjson.com/users](https://dummyjson.com/users) users endpoint. The useQuery hook returns an object with three properties: data, error, and isLoading. The data property contains the response data, error contains any errors that occurred during the request, and isLoading is a boolean that indicates whether the request is still loading.

Declarative Data Fetching

TANStack Query also allows for declarative data fetching, which simplifies the process of handling data in a React application. With TANStack Query, data can be fetched and cached in a centralized location, reducing the need for component-level state management and code repetition.

The useQueryhook can be used to define a query and return a query object that can be used across multiple components. The useQueryhook accepts a query key queryKey , which is a string that uniquely identifies the query. The query key can be used to retrieve the query object from the cache.

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

export default function Users() {
  const { data, error, isLoading } = useQuery({
    queryKey: ["users"],
    queryFn: async () => await axios.get("https://dummyjson.com/users"),
  });

  console.log(data.data.users);

  if (isLoading) {
    return <div>Loading...</div>;
  }

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

  return (
    <ul>
      {data.data.users.map((user) => (
        <li key={user.id} style={{ color: "black" }}>
          {user.firstName}
        </li>
      ))}
    </ul>
  );
}
}

function Posts() {
  const { data, error, isLoading } = useQuery({
    queryKey: ["posts"],
    queryFn:()=> axios.get('https://dummyjson.com/posts')
  });

  if (isLoading) {
    return <div>Loading...</div>;
  }

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

  return (
    <ul>
      {data.map((post) => (
        <li key={post.id}>{post.title}</li>
      ))}
    </ul>
  );
}
Enter fullscreen mode Exit fullscreen mode

TANStack Query simplifies the process of querying APIs and managing data in React applications. With its declarative API and centralized state management system, TANStack Query allows developers to write concise and intuitive code for handling data fetching and caching. By abstracting away the complexity of HTTP requests and response handling, TANStack Query allows developers to focus on building great user experiences.

React Query also removes the need for useStateand useEffecthooks and replace them with a few lines of React Query logic.

If you’re interested to learn more, don’t forget to check out the React Query documentation

Top comments (4)

Collapse
 
codewithonye profile image
code-with-onye

Thanks @syeo66 for the correction, that was a misinformation, TanStack Query actually uses an in-memory cache to store data.

Collapse
 
adityasriivatsalan profile image
adityasriivatsalan

Hi, How does it cache data? Is it through localStorage/IndexedDB?

Collapse
 
syeo66 profile image
Red Ochsenbein (he/him)

By default only in memory. But tanstack query knows the concept of persisters to store and restore the in-memory cache to and from things like sessionStorage/localStorage or IndexedDB

Collapse
 
Sloan, the sloth mascot
Comment deleted